Sub topic 11
When slots are worth it and when they are not
This chapter assumes you know how instances store attributes in __dict__, how __slots__ replaces that dict, and the main side effects: no new attributes, class-variable conflicts, and inheritance rules. Here you will turn those facts into a decision.
What slots buy you
Slots change two things about every instance.
- Memory. The per-instance
__dict__is gone. Attributes sit in fixed positions inside the object, reached through member descriptors on the class. - Typo protection. Assigning a name that is not listed raises
AttributeError.
The memory saving is per instance. It matters only when you create many instances. The numbers below come from the same measurement used earlier in this tutorial. They vary by Python version and implementation, so treat the output as approximate.
import sys
class PlainPoint:
def __init__(self, x, y):
self.x = x
self.y = y
class SlottedPoint:
__slots__ = ("x", "y")
def __init__(self, x, y):
self.x = x
self.y = y
plain = PlainPoint(1, 2)
slotted = SlottedPoint(1, 2)
per_plain = sys.getsizeof(plain) + sys.getsizeof(plain.__dict__)
per_slotted = sys.getsizeof(slotted)
print("plain:", per_plain, "slotted:", per_slotted)
print("saved per instance:", per_plain - per_slotted)
print("saved over 1,000,000 instances (bytes):", (per_plain - per_slotted) * 1_000_000)A saving of tens of bytes per object is irrelevant for a hundred objects. For a million small objects it can be tens of megabytes.
When slots are worth it
Slots are a good fit when most of these hold:
- You create very many instances of the same class, such as nodes in a tree, points, tokens, or rows parsed from a large file.
- Each instance holds only a few attributes, so the dict is a large share of the object's cost.
- The set of attributes is fixed and known when you write the class.
- You have measured memory and found that these objects are a real cost.
When slots are not worth it
Skip slots in these cases.
- Few instances. Configuration objects, services, and singletons gain nothing.
- Dynamic attributes. Code that adds attributes at runtime, such as mixins, plugins, or test doubles that patch objects, fails with
AttributeError. - Deep or third-party hierarchies. One subclass that forgets
__slots__brings back__dict__, which cancels the saving for that class. Mixing slotted classes with multiple inheritance can also fail with a layout conflict when two bases both define non-empty slots. - Features that assume
__dict__. Some libraries and tools readvars(obj)orobj.__dict__. Slotted objects have neither. - Weak references needed. You must add
"__weakref__"to the slots yourself. - You want defaults as class attributes. A class attribute with the same name as a slot raises
ValueError, so defaults move into__init__.
Checking before you commit
A fast way to confirm the choice is to measure the whole workload, not one object. Create the number of instances you expect and compare total memory with tracemalloc.
import tracemalloc
class Plain:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
class Slotted:
__slots__ = ("a", "b", "c")
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def measure(cls, n=200_000):
tracemalloc.start()
objs = [cls(1, 2, 3) for _ in range(n)]
current, _ = tracemalloc.get_traced_memory()
tracemalloc.stop()
return current, len(objs)
for cls in (Plain, Slotted):
current, count = measure(cls)
print(f"{cls.__name__}: {current / count:.0f} bytes per object (including the list)")The list that holds the objects adds the same cost to both runs, so the difference between them is the saving from slots. Run this on your own interpreter, because the result depends on the version.
Keeping the dataclass route in mind
If your class is a plain data holder, @dataclass(slots=True) on Python 3.10 and later gives you slots and normal field defaults in one step. It avoids the class-variable conflict, because the decorator builds the slotted class for you.
A decision sketch
Common mistakes
- Adding slots to a class, then subclassing without
__slots__. The subclass gets a__dict__again. - Claiming a fixed percentage saving. The real figure depends on the Python version and the number of attributes.
- Using slots as a validation tool. Slots block unknown names, but they do not check values or types.
Exercise
A service creates about 5 million small Event objects, each with four fixed attributes, and memory use is a problem. A teammate also wants __slots__ on the AppConfig class, which exists once per process. Which class should get slots, and what should you check on Event after adding them?
Show answer
Add slots to Event, since it has many instances, few fixed attributes, and a measured memory problem. Leave AppConfig alone, because one instance saves almost nothing. On Event, check that every subclass also declares __slots__ (otherwise hasattr(instance, "__dict__") is true again), that no default is set as a class attribute with a slot's name, that nothing else reads vars() or __dict__ on events, and that memory use dropped when measured.
Exercise
Why can sys.getsizeof(obj) alone give a misleading comparison between a plain and a slotted object?
Show answer
For a plain instance, getsizeof reports only the object itself and not its separate __dict__. You must add sys.getsizeof(obj.__dict__) for a fair comparison. Even then, the values the attributes refer to are not counted, and the numbers vary by Python version.