Sub topic 12
`__slots__` and member descriptors
This chapter assumes you know the descriptor protocol (__get__, __set__, __delete__), the data versus non-data distinction, and the full lookup order from earlier chapters. __slots__ is a feature of the class statement that uses that machinery to change where instance attributes are stored.
What `__slots__` does
Normally every instance has a __dict__, a hash table that holds its attributes. Declaring __slots__ tells Python to reserve fixed storage inside each instance for a named set of attributes instead. Python also skips creating the per-instance __dict__.
class Point:
__slots__ = ("x", "y")
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(1, 2)
print(type(Point.__dict__["x"]).__name__) # member_descriptor
print(Point.x) # <member 'x' of 'Point' objects>
print(hasattr(p, "__dict__")) # False
try:
p.z = 3
except AttributeError:
print("cannot add z")For each name in __slots__, the class body creates one object in the class namespace. That object is a member_descriptor. The attribute values live in fixed offsets inside the instance, and the descriptor knows which offset belongs to its name.
Python does not give the instance a __dict__, so there is nowhere to put an undeclared name like z. The assignment goes through the normal object.__setattr__ path, finds no data descriptor named z, finds no dictionary, and raises AttributeError.
Member descriptors are data descriptors
A member_descriptor defines __get__, __set__ and __delete__. That makes it a data descriptor, so it sits at the top of the lookup order. You can call its methods directly, just as you would for a descriptor you wrote yourself.
class Point:
__slots__ = ("x", "y")
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(1, 2)
desc = Point.__dict__["x"]
print(desc.__get__(p, Point)) # 1
desc.__set__(p, 10)
print(p.x) # 10
del p.y
try:
p.y
except AttributeError:
print("y is unset")Two behaviors follow from this design:
- Reading
Point.xon the class passesobj=Noneto__get__. A member descriptor returns itself in that case, which is why the class-level read shows the<member ...>repr. - A slot that has never been assigned, or has been deleted, raises
AttributeErroron read. The descriptor exists, but the storage cell is empty. A slot does not start with a default value.
Because the member descriptor is a data descriptor, it keeps its precedence even when an instance dictionary exists. The next section shows how that can happen.
Slots and a `__dict__` together
You can list "__dict__" in __slots__ to get slot storage for some names and a dictionary for the rest.
class Mixed:
__slots__ = ("x", "__dict__")
m = Mixed()
m.x = "slot"
m.__dict__["x"] = "dict"
m.extra = "in dict"
print(m.x) # slot
print(m.__dict__) # {'x': 'dict', 'extra': 'in dict'}The dictionary holds an entry named x, but the lookup never reaches it. The data descriptor in the class wins, which is the same rule you saw in the first descriptor example of this tutorial. Entries in __dict__ only matter for names that have no data descriptor in the class.
Rules and restrictions
Slots cannot have class-level defaults
A class variable with the same name as a slot would replace the member descriptor in the class namespace, so Python rejects it.
try:
class Bad:
__slots__ = ("x",)
x = 0
except ValueError as e:
print(e) # 'x' in __slots__ conflicts with class variableSet defaults in __init__ instead. If you use dataclasses, the slots=True option (Python 3.10 and later) generates the slots declaration for you and handles defaults.
Inheritance only helps if every class declares slots
A subclass that does not declare __slots__ gets a __dict__ again, which cancels most of the savings. A subclass that does declare __slots__ should list only the new names.
class Base:
__slots__ = ("a",)
class Child(Base):
pass
class SlimChild(Base):
__slots__ = ("b",)
print(hasattr(Child(), "__dict__")) # True
print(hasattr(SlimChild(), "__dict__")) # FalseRe-declaring a name that a base class already put in __slots__ is allowed. It creates a second storage cell and hides the base one, which wastes memory and makes the base class's cell unreachable by normal access.
Two parents with non-empty slots cannot be combined
Each class with slots fixes a memory layout for its instances. Python cannot merge two different non-empty layouts.
class L:
__slots__ = ("a",)
class R:
__slots__ = ("b",)
try:
class Both(L, R):
pass
except TypeError:
print("layout conflict")A parent with __slots__ = () has an empty layout and combines freely. Mixin classes should declare __slots__ = () for this reason.
Weak references need an explicit slot
Instances of a slotted class cannot be weakly referenced unless you ask for it. Add "__weakref__" to __slots__ when you need weakref.ref to work on instances.
import weakref
class NoWeak:
__slots__ = ("x",)
class WithWeak:
__slots__ = ("x", "__weakref__")
try:
weakref.ref(NoWeak())
except TypeError:
print("cannot weakly reference NoWeak")
r = weakref.ref(WithWeak())
print(r() is None) # True: the temporary instance was already collectedA bare string is a single name
__slots__ = "x" declares one slot named x. Some code expects a tuple, so write ("x",) with the trailing comma to avoid ambiguity.
Interactions with other descriptor features
Slots change what is available to features that depend on __dict__.
| Feature | Behavior on a slotted class without `__dict__` |
|---|---|
| `functools.cached_property` | Raises `TypeError` on first access, because it stores its result in the instance `__dict__`. |
| Assigning a new attribute name | Raises `AttributeError`. |
| `vars(obj)` | Raises `TypeError`, because there is no `__dict__`. |
| `property`, `classmethod`, `staticmethod` | Work normally. They live in the class namespace and do not touch the instance. |
| Your own data descriptor | Works. Store values in a slot with a private name, such as `_price`. |
The last row is a useful combination. A validating descriptor like Positive from earlier in this tutorial stores values with setattr(obj, "_price", value). On a slotted class that name must be declared as a slot, because there is no dictionary to hold it.
class Positive:
def __set_name__(self, owner, name):
self.private_name = "_" + name
def __get__(self, obj, objtype=None):
if obj is None:
return self
return getattr(obj, self.private_name)
def __set__(self, obj, value):
if value <= 0:
raise ValueError(f"{self.private_name[1:]} must be positive")
setattr(obj, self.private_name, value)
class Item:
__slots__ = ("_price",)
price = Positive()
def __init__(self, price):
self.price = price
item = Item(4.0)
print(item.price) # 4.0In this class the public name price is a custom descriptor, and the private name _price is a slot with its own member descriptor. Reading item.price calls Positive.__get__, which in turn calls getattr(item, "_price"), which uses the member descriptor. Two data descriptors are chained, and each does a separate job: one validates, the other stores.
When to use slots
Use __slots__ when you create very many small instances and measured memory use matters. Attribute reads on slotted instances are also somewhat faster, though the difference is usually small. Measure with sys.getsizeof plus the size of the dictionary on an unslotted instance, or with tracemalloc, before committing to the restrictions.
Avoid slots when you need dynamic attributes, cached_property, or multiple inheritance from several slotted classes. Slots also do not make a class "safer" in any meaningful way. Their typo-catching effect on assignment is a side effect, and a linter or type checker is a better tool for that.
Debugging checklist
- Check
type(Cls.__dict__["name"]).__name__. If it printsmember_descriptor, the name is a slot. - Check
hasattr(obj, "__dict__"). If it isTrue, some class in the MRO lacks__slots__, so find it with[c for c in type(obj).__mro__ if "__slots__" not in vars(c)]. Remember thatobjectitself will appear in that list. - If a read raises
AttributeErrorfor a name you declared, the slot was never assigned in__init__.
Exercise
A class defines __slots__ = ("x", "__dict__"). You run obj.x = 1 and then obj.__dict__["x"] = 2. What does obj.x return, and why?
Show answer
It returns 1. The slot creates a member descriptor named x in the class, and member descriptors define __set__, so they are data descriptors. A data descriptor takes precedence over an instance __dict__ entry of the same name. The __dict__["x"] entry exists but is never consulted for obj.x.
Exercise
You add @cached_property def total(self): ... to a class that declares __slots__ = ("a", "b") and has no __dict__ slot. What happens on the first access of obj.total, and give two ways to fix it.
Show answer
It raises TypeError, because cached_property stores its result in the instance __dict__ and the instance has none. Fix it by adding "__dict__" to __slots__, or by replacing cached_property with a plain property (or a slot such as _total plus manual caching in a property).