Full answer
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:
slots use less memory: True
AttributeError: 'PointSlots' object has no attribute 'z' and no __dict__ for setting new attributes
FalseMeasured 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.
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