patternpythonModeratepending
Python __slots__ for Memory-Efficient Classes
Viewed 0 times
__slots__memoryoptimizationdataclassslotsperformance
Problem
Python objects use __dict__ for attribute storage by default, consuming significant memory when creating millions of instances.
Solution
Use __slots__ to declare fixed attributes:
Memory savings: 40-60% per instance for simple objects. For 1M instances, this can mean hundreds of MB saved.
# Without __slots__: each instance has a __dict__ (~200+ bytes overhead)
class PointDict:
def __init__(self, x, y):
self.x = x
self.y = y
# With __slots__: no __dict__, fixed memory layout (~56 bytes per instance)
class PointSlots:
__slots__ = ('x', 'y')
def __init__(self, x, y):
self.x = x
self.y = y
# With inheritance
class Point3D(PointSlots):
__slots__ = ('z',) # Only add NEW attributes
def __init__(self, x, y, z):
super().__init__(x, y)
self.z = z
# Combine with dataclasses (Python 3.10+)
from dataclasses import dataclass
@dataclass(slots=True)
class Point:
x: float
y: floatMemory savings: 40-60% per instance for simple objects. For 1M instances, this can mean hundreds of MB saved.
Why
Python's __dict__ is flexible but wasteful when object structure is known at class definition time. __slots__ uses a C-level descriptor protocol that's both faster and more memory-efficient.
Gotchas
- Cannot add arbitrary attributes to slotted instances
- Must redeclare __slots__ in subclasses or they get __dict__ again
- __slots__ and __dict__ can coexist if you include '__dict__' in __slots__
Context
Creating many instances of simple data-holding classes
Revisions (0)
No revisions yet.