__slots__ and Memory Optimization
Use __slots__ to reduce per-instance memory overhead.
The Default __dict__ Overhead
By default every Python instance stores attributes in a __dict__ dictionary, which has significant memory overhead — typically 200-400 bytes per instance.
import sys
class Point:
def __init__(self, x, y): self.x, self.y = x, y
p = Point(1, 2)
print(sys.getsizeof(p.__dict__)) # ~200 bytesDeclaring __slots__
Define __slots__ as a sequence of attribute names. Python allocates a fixed-size array instead of a dict, saving memory.
class SlottedPoint:
__slots__ = ("x", "y")
def __init__(self, x, y):
self.x = x
self.y = y
p = SlottedPoint(1, 2)
print(p.x, p.y) # 1 2
# p.z = 3 # AttributeError: no __dict__All lessons in this course
- How Python Classes Are Created
- Writing Custom Metaclasses
- Descriptors: __get__, __set__, __delete__
- __slots__ and Memory Optimization