Interview frequency: …
Short answer
__slots__ declares a fixed list of attributes and removes the per-instance __dict__, which reduces memory and speeds up access slightly, but it prevents adding dynamic attributes and complicates inheritance.
Explanation
The benefit shows up when you create millions of small objects. The trade-offs: you cannot add undeclared attributes, there are no weak references unless you add __weakref__, and every subclass must declare its own __slots__ or it gets a __dict__ back. It can also conflict with multiple inheritance from classes that have non-empty slots, and with some serialization tools. Measure memory with tracemalloc before adopting it widely.
Code example
class Point:
__slots__ = ("x", "y")
def __init__(self, x: float, y: float):
self.x = x
self.y = y
p = Point(1, 2)
p.z = 3 # AttributeError: 'Point' object has no attribute 'z'Common mistakes
- Adding __slots__ to every class without actually measuring memory.
- Forgetting to declare __slots__ in the subclass, so __dict__ comes back and the benefit is lost.