Sub topic 14
Reducing per-instance overhead with __slots__
This chapter covers what __slots__ changes about how an instance stores its attributes, what it costs you, and when it is worth using. It assumes you know __init__, instance and class attributes, inheritance with super(), and basic dataclass use from the earlier chapters.
Where instance attributes normally live
By default, every instance of a class carries a dictionary named __dict__. Assigning self.x = 1 stores "x" as a key in that dictionary. This is flexible: you can add any attribute to any object at any time. It also costs memory, because each instance owns a dictionary.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(1, 2)
print(p.__dict__) # {'x': 1, 'y': 2}
p.color = "red" # allowed: the dict simply grows
print(p.__dict__) # {'x': 1, 'y': 2, 'color': 'red'}If your program creates a few objects, this overhead does not matter. If it creates millions of small objects, such as points, tokens, or graph nodes, the per-instance dictionary can be a large part of the memory use.
Declaring slots
Setting __slots__ in the class body tells Python the exact attribute names instances will have. Python then reserves a fixed space for those attributes inside each instance. It does not create a __dict__.
class Point:
__slots__ = ("x", "y")
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(1, 2)
print(p.x, p.y) # 1 2
print(hasattr(p, "__dict__")) # False
try:
p.z = 3
except AttributeError as exc:
print("error:", exc)The last line prints an AttributeError. The exact wording differs between Python versions. Slots therefore do two things: they save memory and they close the set of allowed attribute names. A typo such as p.xx = 5 now fails instead of silently creating a new attribute.
Each name in __slots__ becomes a descriptor on the class. A descriptor is an object that controls how an attribute is read and written. You can see them on the class:
print(Point.x) # <member 'x' of 'Point' objects>
print(Point.__slots__) # ('x', 'y')A slot that was never assigned raises AttributeError when read, just like a missing normal attribute:
q = Point.__new__(Point) # skip __init__ on purpose
try:
print(q.x)
except AttributeError:
print("slot x is empty")Measuring the saving
Measure on your own Python version rather than trusting a number from a blog post. Recent Python versions optimize instance dictionaries, so the gap is smaller than it used to be. The tracemalloc module reports memory allocated by Python code:
import tracemalloc
class WithDict:
def __init__(self, x, y):
self.x = x
self.y = y
class WithSlots:
__slots__ = ("x", "y")
def __init__(self, x, y):
self.x = x
self.y = y
def bytes_per_instance(cls, n=100_000):
tracemalloc.start()
before = tracemalloc.get_traced_memory()[0]
objects = [cls(1, 2) for _ in range(n)]
after = tracemalloc.get_traced_memory()[0]
tracemalloc.stop()
del objects
return (after - before) / n
print("dict :", round(bytes_per_instance(WithDict)))
print("slots:", round(bytes_per_instance(WithSlots)))The slotted class normally reports a clearly smaller number. The measurement includes the 8-byte list slot that points to each object, which is the same for both classes. Attribute access on slotted instances is also usually slightly faster, but the difference is small and rarely decides anything. Memory is the real reason to use slots.
| Aspect | Default (`__dict__`) | With `__slots__` |
|---|---|---|
| Storage | One dictionary per instance | Fixed space per declared name |
| New attribute names at runtime | Allowed | `AttributeError` |
| Memory per instance | Higher | Lower |
| Weak references | Supported | Only if `"__weakref__"` is a slot |
| Class-level default for same name | Allowed | Conflict error |
Gotchas
Defaults cannot be class attributes with the same name
A slot is a class-level descriptor. A class attribute with the same name would replace it, so Python rejects the combination when the class is created:
try:
class Bad:
__slots__ = ("x",)
x = 0
except ValueError as exc:
print("error:", exc) # 'x' in __slots__ conflicts with class variableSet defaults in __init__ instead. The @dataclass(slots=True) option, shown below, handles this for you.
Inheritance can silently undo the saving
A subclass only avoids __dict__ if it also declares __slots__. If any class in the chain lacks __slots__, instances get a __dict__.
class Base:
__slots__ = ("a",)
class LooseChild(Base): # no __slots__ here
pass
class TightChild(Base):
__slots__ = ("b",) # only the NEW names
print(hasattr(LooseChild(), "__dict__")) # True
print(hasattr(TightChild(), "__dict__")) # FalseTwo rules follow:
- List only new names in a subclass. Repeating a name from the parent creates a second, hidden slot and wastes memory.
- If a subclass adds no attributes, write
__slots__ = ()so it stays dictionary-free.
A plain parent class without __slots__ also gives every child a __dict__, whatever the child declares. Check that the whole hierarchy uses slots, including mixins.
Multiple inheritance is restricted
Two parents that each define non-empty slots cannot be combined, because Python cannot lay out both sets of fields in one object:
class A:
__slots__ = ("a",)
class B:
__slots__ = ("b",)
try:
class C(A, B):
pass
except TypeError as exc:
print("error:", exc) # multiple bases have instance lay-out conflictMixin classes used with slots should declare __slots__ = () so they add no storage.
Weak references and dynamic attributes must be requested
Weak references, created with the weakref module, need a special hidden attribute called __weakref__. Slotted classes do not have it unless you ask:
import weakref
class Node:
__slots__ = ("value", "__weakref__")
def __init__(self, value):
self.value = value
n = Node(5)
ref = weakref.ref(n)
print(ref().value) # 5You can also list "__dict__" as a slot to get a dictionary back for extra attributes. That keeps the fast fixed slots for the known names but gives up part of the memory saving and the typo protection.
Tools that expect `__dict__`
Code that reads vars(obj) or obj.__dict__ fails on slotted instances with a TypeError or AttributeError. Some serialization and debugging helpers do this. When you need the values, loop over the slot names:
def slot_values(obj):
return {name: getattr(obj, name) for name in type(obj).__slots__}
print(slot_values(Point(1, 2))) # {'x': 1, 'y': 2}This helper covers one class only. For a hierarchy, walk type(obj).__mro__ and collect each class's __slots__.
Slots with dataclasses
From Python 3.10, @dataclass(slots=True) generates __slots__ from the fields for you. Defaults and default_factory still work, because the decorator builds the class correctly:
from dataclasses import dataclass, field
@dataclass(slots=True)
class Order:
order_id: int
items: list[str] = field(default_factory=list)
paid: bool = False
o = Order(1)
o.items.append("book")
print(o) # Order(order_id=1, items=['book'], paid=False)
print(hasattr(o, "__dict__")) # FalseThe decorator creates a new class object instead of modifying the one you wrote. Code that holds a reference to the original class, or that calls super() without arguments inside methods on some Python versions, can behave unexpectedly. Test inheritance and super() calls if you combine them with slots=True.
When to use slots
Use __slots__ when all of these hold:
- You create very many instances of the class, typically tens of thousands or more.
- The set of attributes is small and fixed.
- You have measured memory use and it matters.
Avoid it when the class is created only a few times, when you rely on adding attributes dynamically, when you need broad compatibility with tools that inspect __dict__, or when the hierarchy uses multiple inheritance. For most classes the default is the better choice. Add slots after profiling shows a problem, not as a habit.
Exercise
A class Base declares __slots__ = ("a",). You write class Child(Base): pass and create a million Child instances expecting a memory saving. Why might it not appear, and how do you fix it?
Show answer
Child does not declare __slots__, so Python gives each instance a __dict__ anyway, which removes most of the saving. Fix it by adding __slots__ = () to Child if it adds no attributes, or __slots__ = ("b",) listing only the new names if it does.
Exercise
This code raises an error when the class is defined. What is the error, and what is the smallest change that fixes it while keeping a default value of 0 for count?
class Counter:
_slots_ = ("count",)
count = 0
Show answer
Python raises ValueError because the name count in __slots__ conflicts with the class variable count. Remove the class-level count = 0 and set the default in an initializer: def __init__(self): self.count = 0.
Exercise
You add __slots__ = ("value",) to a Node class, and later weakref.ref(node) fails with a TypeError. What do you add to __slots__ to allow weak references?
Show answer
Add the name "__weakref__", so __slots__ = ("value", "__weakref__").