Sub topic 12
__slots__ and member descriptors
This chapter assumes you know how obj.name resolves through the type, the instance __dict__ and __getattr__. It also assumes you know the difference between data and non-data descriptors. Here you will see that __slots__ is an application of that same machinery.
What __slots__ changes
Normally each instance carries a __dict__ that stores its attributes. Declaring __slots__ tells Python to reserve fixed storage for the named attributes and to skip 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(p.x) # 1
print(hasattr(p, "__dict__")) # False
print(type(Point.__dict__["x"]).__name__) # member_descriptor
print(Point.x) # <member 'x' of 'Point' objects>
try:
p.z = 3
except AttributeError:
print("cannot add z")When the class body is created, Python adds one member_descriptor to the class namespace for each slot name. The values live in fixed positions inside the instance. The descriptor knows which position to read and write.
Why it follows the normal lookup rules
A member descriptor defines __get__, __set__ and __delete__, so it is a data descriptor. In the lookup order, a data descriptor found on the type wins before the instance __dict__ is consulted. With slots there is usually no instance __dict__ to consult anyway.
Called by hand, the descriptor behaves like any other:
member = Point.__dict__["x"]
print(member.__get__(p, Point)) # 1
member.__set__(p, 10)
print(p.x) # 10Reading a slot that was never assigned raises AttributeError. The descriptor exists, but its storage is empty.
empty = Point.__new__(Point)
try:
empty.x
except AttributeError:
print("slot x is unset")Behaviors to know
- Inheritance. A subclass that does not declare
__slots__gets a__dict__again, which removes most of the memory savings. - Class variables conflict. A slot name cannot also be a class attribute, because both would occupy the same name in the class namespace.
- Weak references. Instances of slotted classes cannot be weakly referenced unless
"__weakref__"is listed in__slots__. - Defaults. Because of the conflict above, set defaults in
__init__, not as class attributes.
class Base:
__slots__ = ("x",)
class Child(Base):
pass
print(hasattr(Child(), "__dict__")) # True
try:
class Bad:
__slots__ = ("x",)
x = 0
except ValueError as exc:
print(exc) # 'x' in __slots__ conflicts with class variableWhen to use it
Use __slots__ when you create very many small instances and want lower memory use, or when you want to reject misspelled attribute names. Do not use it only to look "optimized". It restricts dynamic features such as adding arbitrary attributes, and some tools that expect __dict__ behave differently with it.
Exercise
Given class Point: __slots__ = ("x", "y") and p = Point(), what does p.x do before any assignment, and why does assigning p.__dict__["x"] = 5 not help?
Show answer
p.x raises AttributeError because the member descriptor on the class finds its storage empty. Assigning through p.__dict__ is not possible, because instances of a slotted class have no __dict__. Even if one existed, the member descriptor is a data descriptor, so it would take precedence over an instance dictionary entry.