Mastery
Mastery/Python/A. Object model, identity & memory
T2 · intermediate depth

__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.

python
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.

Interview angle

A good systems-thinking question for a candidate who's used Python at any real scale: "you're creating millions of small objects — what's one language-level change that could meaningfully cut memory usage?" __slots__ is the right answer, and knowing the actual tradeoff (no dynamic attributes, tricky multiple inheritance) shows they understand it's a deliberate design choice, not a free optimization.

In the industry

__slots__ is standard practice in performance-sensitive libraries that create huge numbers of small objects — ORMs, parsers, data-processing libraries, and game engines all use it for exactly this reason. It's less common in typical application code, where the flexibility of __dict__ usually outweighs the memory savings — reached for specifically when profiling shows object overhead actually matters, not applied reflexively to every class.