patternpythonnoneTip
__slots__ in Dataclasses for Memory Efficiency
Viewed 0 times
Python 3.10+
__slots__slotsdataclassesmemory optimizationPython 3.10
Error Messages
Problem
Python objects store instance attributes in a __dict__ per instance, consuming significant memory when millions of instances are created. dataclasses do not enable slots by default.
Solution
Use slots=True in dataclasses (Python 3.10+) to eliminate per-instance __dict__.
from dataclasses import dataclass
import sys
@dataclass
class Point:
x: float
y: float
@dataclass(slots=True)
class PointSlotted:
x: float
y: float
p1 = Point(1.0, 2.0)
p2 = PointSlotted(1.0, 2.0)
print(sys.getsizeof(p1)) # ~56 bytes plus __dict__ ~232 bytes
print(sys.getsizeof(p2)) # ~56 bytes no __dict__
# Slotted classes cannot have arbitrary attributes:
p2.z = 3.0 # AttributeError: 'PointSlotted' has no attribute 'z'
# For Python 3.9 and earlier:
@dataclass
class LegacySlotted:
__slots__ = ('x', 'y')
x: float
y: floatWhy
Python instances store attributes in a dict, which has ~200 bytes of overhead. __slots__ replaces the dict with fixed-size array slots, reducing memory 50-80% for large numbers of instances.
Gotchas
- slots=True requires Python 3.10+ — use attrs slots=True for compatibility with older versions.
- Inheritance of slotted dataclasses requires the parent to also use slots — mixing breaks the optimization.
- Slotted classes cannot add arbitrary attributes after creation.
Revisions (0)
No revisions yet.