If you're instantiating millions of objects, defining __slots__ in your class
prevents Python from creating a per-instance __dict__ — saving significant memory.
Example
class Point:
__slots__ = ('x', 'y')
def __init__(self, x, y):
self.x, self.y = x, y
Benchmarks show ~40–50% RAM reduction vs. a regular class when creating 1M+ instances.
Why It Works
- Normal classes store instance attributes in a
__dict__, which has overhead -
__slots__replaces that dict with fixed-size memory slots per attribute - Less memory allocation = faster GC and better cache locality too
Tradeoffs
- ❌ You lose dynamic attribute assignment (
obj.new_attr = valraisesAttributeError) - ❌ Pickling and multiple inheritance need extra care
- ❌ Not worth it for small scripts — only shines at volume
Best Use Cases
✅ High-throughput data pipelines
✅ Game entity systems
✅ ML feature objects
✅ Anything spawning massive numbers of instances
Tested on CPython 3.11/3.12. Results vary slightly by platform.
Top comments (0)