What does `__slots__` do in Python, and when should you use it?
`__slots__` replaces the per-instance `__dict__` with a fixed-size C array of slot descriptors, cutting memory usage per instance by 40–60% and speeding up attribute access. Use it for classes that create many small, fixed-attribute instances — but be aware it prevents dynamic attribute assignment and complicates multiple inheritance.
How to think about it
This question shows up most often at companies that work at scale — streaming pipelines, graph algorithms, or any system that creates millions of small objects. The interviewer wants to know you understand why regular instances are expensive (the __dict__) and what __slots__ trades away to fix that.
Every ordinary Python instance carries a __dict__ — a hash map that stores its attributes dynamically. That hash map has real overhead: on CPython it costs around 200–230 bytes even when empty. For millions of small objects (graph nodes, events, sensor readings), this dominates memory.
__slots__ tells Python to replace __dict__ with compact C-level slot descriptors allocated once per class, not once per instance.
Measure the difference live
Rules and caveats
- Subclasses that do not redeclare
__slots__regain__dict__— defeating the optimisation. - To allow arbitrary extra attributes alongside slots, include
"__dict__"in__slots__explicitly. __weakref__support is also lost unless you include"__weakref__"in__slots__.- Python 3.10+
@dataclass(slots=True)gives you slots without writing them manually — cleaner for new code.
from dataclasses import dataclass, field
@dataclass(slots=True)
class Point:
x: float
y: float
When to use it
Reach for __slots__ when you are creating tens of thousands or more instances of a class with a known, fixed set of attributes. Typical examples: nodes in a graph, rows in an in-memory store, events in a streaming pipeline.