Sub topic 14
Reducing per-instance overhead with `__slots__`
This chapter assumes you know how __init__, instance attributes, and inheritance work. It also assumes you know that Python normally stores an instance's attributes in a dictionary.
How instances store attributes
By default, every instance has a __dict__, a dictionary mapping attribute names to values. This makes Python flexible, because you can add attributes at any time. Each instance pays for its own dictionary, though. If your program creates hundreds of thousands of small objects, that cost adds up.
__slots__ is a class attribute that lists the only attribute names instances may have. Python then stores the values in fixed positions inside the object and creates no per-instance __dict__.
Declaring slots
class Point:
__slots__ = ("x", "y")
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(1, 2)
p.x = 10
print(p.x) # 10
print(hasattr(p, "__dict__")) # False
try:
p.z = 3
except AttributeError:
print("cannot add z") # cannot add zThe class works as before, but assigning a name that is not in __slots__ raises AttributeError. This catches typos like p.xx = 5, but it also removes the ability to attach arbitrary attributes.
Measuring the saving
The saving is the dictionary you no longer allocate. This script compares the two layouts. The exact byte counts depend on your Python version, so it prints only the comparison.
import sys
class Plain:
def __init__(self, x, y):
self.x = x
self.y = y
class Slotted:
__slots__ = ("x", "y")
def __init__(self, x, y):
self.x = x
self.y = y
plain, slotted = Plain(1, 2), Slotted(1, 2)
plain_size = sys.getsizeof(plain) + sys.getsizeof(plain.__dict__)
slotted_size = sys.getsizeof(slotted)
print(slotted_size < plain_size) # Truesys.getsizeof on the plain instance does not include its dictionary, so the script adds the two sizes. The values themselves, such as the integers, cost the same either way.
Rules and gotchas
- Inheritance. If a subclass does not define
__slots__, its instances get a__dict__again, and you lose the saving. Write__slots__ = ()in a subclass that adds no attributes. - Class-level defaults. A slot name cannot also be a class attribute with a default value. Python raises
ValueError. Set defaults in__init__instead. - Weak references. Slotted instances cannot be weakly referenced unless you include
"__weakref__"in__slots__. - Multiple inheritance. Two parents that both define non-empty slots usually cannot be combined, because their memory layouts conflict.
class Base:
__slots__ = ("a",)
class Child(Base): # no __slots__: gets a __dict__
pass
class SlimChild(Base):
__slots__ = ("b",) # adds only b; still no __dict__
print(hasattr(Child(), "__dict__")) # True
print(hasattr(SlimChild(), "__dict__")) # FalseSlots with dataclasses
Since Python 3.10, a dataclass can generate the slots for you:
from dataclasses import dataclass
@dataclass(slots=True)
class Pixel:
x: int
y: int
px = Pixel(1, 2)
print(px) # Pixel(x=1, y=2)
print(hasattr(px, "__dict__")) # FalseNote that slots=True creates a new class object. Code that uses zero-argument super() inside the class can behave unexpectedly on versions before 3.14, so test such classes.
Deciding whether to use it
Summary
Use __slots__ to remove the per-instance dictionary when you have a very large number of small, fixed-shape objects. Keep the whole inheritance chain slotted, avoid class-level defaults for slot names, and measure before you commit.
Exercise
A class Base defines __slots__ = ("a",). You write class Child(Base): pass and find that Child() instances still have a __dict__. Why does this happen, and how do you fix it?
Show answer
A subclass that does not declare __slots__ gets a regular __dict__ again, even if its parent uses slots. Add __slots__ = () to Child (or list its new attribute names) so its instances have no __dict__.
Exercise
Why does this class raise an error when it is defined? class C: __slots__ = ("n",); n = 0
Show answer
A name listed in __slots__ cannot also be a class attribute. The slot creates a descriptor named n on the class, which conflicts with the class variable, so Python raises ValueError. Assign the default in __init__ instead.