← Back to Python, page 4

python-0068 · Hard senior

Reduce memory for millions of small objects with __slots__, and explain the trade-offs.

__slots__ declares a fixed set of attribute names, so instances store attributes in a compact array instead of a per-instance __dict__. That saves memory and slightly speeds attribute access, but instances cannot gain new attributes, and multiple inheritance with slots needs care. dataclass(slots=True) applies it automatically.

Full answer
python
import sys, tracemalloc
from dataclasses import dataclass

class PointDict:
    def __init__(self, x, y): self.x, self.y = x, y

class PointSlots:
    __slots__ = ("x", "y")
    def __init__(self, x, y): self.x, self.y = x, y

def measure(cls, n=100_000):
    tracemalloc.start()
    objs = [cls(i, i) for i in range(n)]
    size = tracemalloc.get_traced_memory()[0]
    tracemalloc.stop()
    return size

d, s = measure(PointDict), measure(PointSlots)
print("slots use less memory:", s < d)
p = PointSlots(1, 2)
try:
    p.z = 3
except AttributeError as e:
    print("AttributeError:", e)

@dataclass(slots=True)
class Reading:
    sensor: int
    value: float
print(hasattr(Reading(1, 2.0), "__dict__"))

Output:

text
slots use less memory: True
AttributeError: 'PointSlots' object has no attribute 'z' and no __dict__ for setting new attributes
False

Measured with tracemalloc, a hundred thousand slotted points use less memory than ordinary instances; the run prints a comparison rather than byte counts, which vary between builds. The gap is smaller on Python 3.11+ than on older versions, because ordinary instances now keep attributes inline and create a real __dict__ only when something asks for it, so measure on the version in production. Assigning an undeclared attribute fails, which can also catch typos. dataclass(slots=True) produces instances without __dict__. Trade-offs: no dynamic attributes, weak references need '__weakref__' in the slots, and every class in a hierarchy must declare slots for the saving to hold. For very large numeric data, arrays or NumPy beat any per-object layout.

python
import sys, tracemalloc
from dataclasses import dataclass

class PointDict:
    def __init__(self, x, y): self.x, self.y = x, y

class PointSlots:
    __slots__ = ("x", "y")
    def __init__(self, x, y): self.x, self.y = x, y

def measure(cls, n=100_000):
    tracemalloc.start()
    objs = [cls(i, i) for i in range(n)]
    size = tracemalloc.get_traced_memory()[0]
    tracemalloc.stop()
    return size

d, s = measure(PointDict), measure(PointSlots)
print("slots use less memory:", s < d)
p = PointSlots(1, 2)
try:
    p.z = 3
except AttributeError as e:
    print("AttributeError:", e)

@dataclass(slots=True)
class Reading:
    sensor: int
    value: float
print(hasattr(Reading(1, 2.0), "__dict__"))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Slots remove the per-instance __dict__
  • Large memory savings for many objects
  • No new attributes at runtime
  • dataclass(slots=True) applies it
  • Arrays beat objects for bulk numbers

Common mistakes

  • Adding slots to classes that need dynamic attributes
  • Forgetting slots in subclasses

Follow-ups

  • How do slots interact with inheritance?
  • When is NumPy the better answer?

Tips

  • Measure before and after