How does __slots__ interact with magic methods and instance attribute storage?
Short answer
__slots__ declares a fixed set of attribute names, replacing the per-instance __dict__ with more memory-efficient fixed-size slots and preventing arbitrary new attributes from being set.
Advertisement
AModel answer
__slots__ declares a fixed set of attribute names, replacing the per-instance __dict__ with more memory-efficient fixed-size slots and preventing arbitrary new attributes from being set. It doesn't itself define magic methods, but it affects ones related to attribute storage: __getattr__/__setattr__ still work as fallbacks, but pickling, copying, and cached_property require special handling since there's no __dict__ to store extra state.
class Point:
__slots__ = ('x', 'y')
def __init__(self, x, y):
self.x, self.y = x, y
p = Point(1, 2)
try:
p.z = 3 # AttributeError: no __dict__, z not in __slots__
except AttributeError as e:
print(e)Real-world example
A high-volume data processing pipeline creating millions of small Point objects uses __slots__ to cut per-instance memory overhead significantly compared to default __dict__-based instances.
Likely follow-ups
- How does __slots__ interact with inheritance from a class without __slots__?
- Why can't you use cached_property with __slots__ directly?
Related topics