__slots__
__slots__ replaces the per-instance __dict__ with fixed-size arrays, reducing memory by 40–50% for large numbers of instances.
__slots__ replaces the per-instance __dict__ with fixed-size arrays, reducing memory by 40–50% for large numbers of instances.
class Point:
__slots__ = ("x", "y")
def __init__(self, x: float, y: float):
self.x = x; self.y = y
# Memory comparison (10 million instances):
# Without __slots__: ~3.5 GB
# With __slots__: ~1.7 GB
# Cannot add arbitrary attributes
p = Point(1.0, 2.0)
p.z = 3.0 # AttributeError
import sys
sys.getsizeof(Point(1,2)) # ~56 bytes vs ~232 bytes without slots
Use __slots__ for classes that will have millions of instances — sensors, events, records, coordinates.