Memory Modelmedium

__slots__

A class-level declaration that replaces the per-instance __dict__ with fixed-size descriptor slots, reducing memory usage.

Memory anchor

__slots__ = assigned parking spots instead of a free-for-all parking garage (__dict__). Fixed spots use way less space, but you can't park anywhere you want anymore.

Expected depth

Normally each instance has a __dict__ (a hash table) storing its attributes — flexible but memory-heavy. With __slots__ = ('x', 'y'), the class uses C-level struct slots instead. Result: ~40–50% less memory per instance, faster attribute access, and no __dict__ (so no arbitrary attribute assignment).

Deep — senior internals

Slots use descriptors (slot_wrapper objects) at the class level. __slots__ only applies to the class that declares it — subclasses still get __dict__ unless they also declare __slots__. Mixing __slots__ classes in multiple inheritance is tricky — slots from different bases can conflict. Pickle works with slots but requires custom __getstate__/__setstate__. Slots don't work with weak references unless '__weakref__' is included in __slots__.

🎤Interview-ready answer

Adding __slots__ to a class replaces each instance's __dict__ with fixed descriptor slots. This saves ~40-50% memory when you have millions of instances with known, fixed attributes — think data objects, lightweight value types. The trade-off: you can't add arbitrary attributes at runtime. I'd use it in data-intensive code — e.g., a Point class in a geometry engine.

Common trap

__slots__ on a subclass doesn't eliminate __dict__ unless the parent also uses __slots__. Inheriting from a regular class and adding __slots__ to the subclass still gives every instance a __dict__.