__slots__: memory savings, what you lose
By default, every instance carries its own __dict__ for attribute storage -- flexible, but that dict has
real memory overhead. __slots__ tells Python to allocate fixed-size storage for exactly the named
attributes instead, skipping the per-instance dict entirely. The tradeoffs: no __dict__ (so no adding
attributes that weren't declared), and multiple inheritance from more than one slotted class with
overlapping slots doesn't work.
import sys
class WithDict:
def __init__(self, x, y):
self.x, self.y = x, y
class WithSlots:
__slots__ = ("x", "y")
def __init__(self, x, y):
self.x, self.y = x, y
wd = WithDict(1, 2)
ws = WithSlots(1, 2)
print("WithDict has __dict__:", hasattr(wd, "__dict__"))
print("WithSlots has __dict__:", hasattr(ws, "__dict__"))
try:
ws.z = 3
except AttributeError as e:
print("can't add attributes not declared in __slots__:", e)
print("size of a WithDict instance (object + its dict):", sys.getsizeof(wd) + sys.getsizeof(wd.__dict__), "bytes")
print("size of a WithSlots instance: ", sys.getsizeof(ws), "bytes")
The savings compound fast: if you're creating millions of small objects (parsed records, graph nodes, tuples-with-names), __slots__ is a real, measurable memory optimization -- not a micro-tweak.