Sub topic 10
Reducing per-instance memory with __slots__
This chapter assumes you know how instances store attributes in a __dict__, how classes and inheritance work, and how to measure memory with sys.getsizeof and tracemalloc. Earlier chapters covered those tools. Here you will use them to see what __slots__ saves, and you will learn what it costs.
Where per-instance memory goes
A normal instance of a user-defined class stores its attributes in a dictionary called __dict__. Each instance gets its own dictionary, and a dictionary is a hash table with its own header and storage. For a class that creates millions of small objects, the dictionary can cost more than the data.
__slots__ is a class attribute that declares a fixed set of attribute names. CPython then reserves one pointer-sized field per name directly inside the instance. It does not create a __dict__ for each instance.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
class SlotPoint:
__slots__ = ("x", "y")
def __init__(self, x, y):
self.x = x
self.y = y
print(hasattr(Point(1, 2), "__dict__")) # True
print(hasattr(SlotPoint(1, 2), "__dict__")) # FalseEach name in __slots__ becomes a descriptor on the class. A descriptor is an object that controls attribute access. SlotPoint.x is a member descriptor that reads and writes the field at a fixed offset inside the instance.
Measuring the difference
sys.getsizeof is shallow, so getsizeof(obj) alone does not show the dictionary's cost. Use tracemalloc instead. It counts every allocation made while it is running, including the instance, its dictionary, and any other objects created for it.
import tracemalloc
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
class SlotPoint:
__slots__ = ("x", "y")
def __init__(self, x, y):
self.x = x
self.y = y
def bytes_per_instance(cls, n=100_000):
tracemalloc.start()
objs = [cls(i, i) for i in range(n)]
current, _peak = tracemalloc.get_traced_memory()
tracemalloc.stop()
return current / len(objs)
print("regular:", round(bytes_per_instance(Point)))
print("slotted:", round(bytes_per_instance(SlotPoint)))Both versions create the same integer objects and the same outer list, so those costs cancel in the comparison. The slotted version should report fewer bytes per instance. The exact figures depend on your Python version and platform, so run it yourself instead of trusting a number from a book.
What you give up
The saving comes from fixing the layout at class-creation time. Several behaviors change as a result.
No new attributes
Assigning a name that is not in __slots__ raises AttributeError. This can catch typos, but it also breaks code that attaches ad hoc attributes.
class SlotPoint:
__slots__ = ("x", "y")
p = SlotPoint()
p.x = 1
try:
p.z = 3
except AttributeError as exc:
print("error:", exc)
try:
print(p.y) # declared but never assigned
except AttributeError as exc:
print("error:", exc)A slot that has not been assigned is empty, and reading it raises AttributeError, as the second block shows. Slots do not default to None.
No default values as class attributes
You cannot use a class attribute as a default for a name that is also a slot. The class body would define the same name twice, and CPython rejects that.
try:
class Bad:
__slots__ = ("x",)
x = 0
except ValueError as exc:
print("error:", exc)Set defaults in __init__ instead.
No weak references by default
An instance can only be the target of a weak reference if it has a __weakref__ field. Regular classes get one automatically. Slotted classes do not, unless you add "__weakref__" to __slots__.
import weakref
class Plain:
__slots__ = ("x",)
class Referenceable:
__slots__ = ("x", "__weakref__")
try:
weakref.ref(Plain())
except TypeError as exc:
print("error:", exc)
obj = Referenceable()
ref = weakref.ref(obj)
print(ref() is obj) # TrueAdding "__weakref__" costs one more pointer per instance. You can also add "__dict__" to get a dictionary back, but that undoes most of the saving.
Inheritance rules
Inheritance is where __slots__ most often goes wrong.
- A subclass that does not define
__slots__gets a__dict__again, even if its base class is slotted. The base class's slots still work, but the subclass loses the memory saving. - A subclass that defines
__slots__should list only the new names. Repeating a name already declared in a base wastes space, because the subclass creates a second, hidden field. - To keep a subclass slotted without adding fields, write
__slots__ = (). - If a base class has a
__dict__, the subclass has one too, whatever it declares.
class Base:
__slots__ = ("x",)
class Leaky(Base):
pass # no __slots__, so instances get a __dict__
class Tight(Base):
__slots__ = ("y",)
print(hasattr(Leaky(), "__dict__")) # True
print(hasattr(Tight(), "__dict__")) # FalseMultiple inheritance is restricted. If two base classes each define non-empty __slots__, creating a class that inherits from both fails, because CPython cannot merge their field layouts.
class A:
__slots__ = ("a",)
class B:
__slots__ = ("b",)
try:
class C(A, B):
pass
except TypeError as exc:
print("error:", exc)A common design is to give mixin classes __slots__ = (). Such a mixin adds behavior without adding fields, so it combines freely with one slotted base.
Dataclasses and pickling
Since Python 3.10, the dataclass decorator can generate __slots__ for you. This avoids the class-attribute conflict described above, because the decorator rebuilds the class with the slots in place.
from dataclasses import dataclass
@dataclass(slots=True)
class Vec:
x: float = 0.0
y: float = 0.0
v = Vec(1.0, 2.0)
print(v)
print(hasattr(v, "__dict__")) # FalseBecause slots=True creates a new class object, code inside the class that refers to its own name through zero-argument super() can misbehave on older versions. Test those cases.
Pickling slotted objects works with protocol 2 and later, which is the default in modern Python. Under protocol 0 or 1 it fails, because those protocols look for __dict__. If you must support them, define __getstate__ and __setstate__.
When to use `__slots__`
Use it when all of these hold:
- The program creates a very large number of instances of one class, typically hundreds of thousands or more.
- The set of attributes is fixed and known when you write the class.
- A measurement with
tracemallocon your target Python version shows a worthwhile saving.
Do not use it on classes with few instances, on classes that rely on dynamic attributes, or as a way to prevent mistakes. For a handful of objects, the saving is a few hundred bytes and not worth the restrictions.
If the real problem is that you hold too many objects at once, a different fix may fit better. Generating values lazily, covered in the next chapter, avoids creating the objects at all.
| Aspect | Regular class | Slotted class |
|---|---|---|
| Attribute storage | Per-instance `__dict__` | Fixed fields in the instance |
| Add new attributes at runtime | Yes | No |
| Weak references | Yes | Only with `__weakref__` in `__slots__` |
| Class-attribute defaults for the same name | Allowed | Raises `ValueError` |
| Multiple inheritance | Flexible | Layout conflicts if bases have slots |
| Memory per instance | Higher | Lower, by an amount that depends on the version |
Exercise
A class Base defines __slots__ = ("x",). A subclass Child(Base) is written with a body of only pass, and you create a million Child instances. Why does memory use stay high, what is the smallest change that fixes it, and how would you verify the fix?
Show answer
A subclass without its own __slots__ gets a __dict__ for each instance, so the dictionary cost returns even though Base is slotted. Add __slots__ = () to Child (or list any new field names there). To verify, check that hasattr(Child(), "__dict__") is False, then compare bytes per instance before and after with tracemalloc, as in the measurement example above.
Exercise
You add __slots__ = ("name",) to a class and later call weakref.ref(instance). It raises TypeError. What causes the error, and what do you change?
Show answer
A slotted class has no __weakref__ field unless you declare one. Change the declaration to __slots__ = ("name", "__weakref__"). This costs one extra pointer per instance.