Sub topic 9
Slotted dataclasses with slots=True
This chapter assumes you know how __slots__ replaces the instance __dict__. It also assumes you know why a class attribute that shares a name with a slot raises ValueError, and how slots behave under inheritance. You should be comfortable with the basics of @dataclass: annotated fields, defaults, and the generated __init__, __repr__ and __eq__.
Why dataclasses and slots need help to combine
Dataclasses and __slots__ both target classes that mostly hold data. Writing __slots__ by hand next to dataclass fields breaks as soon as a field has a default. Here is the conflict from the earlier chapter, in dataclass form:
from dataclasses import dataclass
try:
@dataclass
class Bad:
__slots__ = ("x", "y")
x: int
y: int = 0
except ValueError as exc:
print("ValueError:", exc)The class body assigns y = 0, so y is both a slot and a class variable. type() rejects that while it builds the class, before the @dataclass decorator ever runs. You could drop the defaults and write __init__ yourself, but that removes the main benefit of dataclasses.
Python 3.10 added a slots parameter to the decorator to solve this:
from dataclasses import dataclass
@dataclass(slots=True)
class Point:
x: int
y: int = 0
p = Point(1)
print(p)
print(Point.__slots__)
print(hasattr(p, "__dict__"))
print(type(Point.__dict__["y"]))
try:
p.z = 3
except AttributeError as exc:
print("AttributeError:", type(exc).__name__)The default y = 0 works, the instance has no __dict__, and y on the class is a member descriptor, as it is for any slot. On Python 3.9 and earlier, dataclass(slots=True) raises TypeError: dataclass() got an unexpected keyword argument 'slots'.
What the decorator does
A class cannot gain __slots__ after it exists. The slot descriptors are created inside type.__new__, and the instance layout is fixed at that moment. So dataclass(slots=True) cannot modify your class. It builds a second class and returns that one instead.
The key steps are:
- The decorator reads the fields and their defaults, then removes the default values from the copied namespace. This avoids the
ValueErrorshown above. - It sets
__slots__to the field names that no base class already provides as a slot. - It stores the defaults on the generated
__init__signature, not on the class. This is whyPoint.yis a descriptor and not0. - It creates the new class and returns it.
You cannot combine slots=True with a hand-written __slots__. The decorator raises TypeError: ... already specifies __slots__.
Defaults and factories
Both plain defaults and default_factory work. The same rules apply as for normal dataclasses: a mutable default needs a factory, and fields without defaults cannot follow fields with defaults unless you use kw_only.
from dataclasses import dataclass, field, fields
@dataclass(slots=True)
class Inventory:
owner: str
items: list[str] = field(default_factory=list)
capacity: int = 10
a = Inventory("ana")
b = Inventory("ben")
a.items.append("lamp")
print(a)
print(b)
for f in fields(Inventory):
print(f.name, f.default, f.default_factory)Each instance gets its own list because the generated __init__ calls the factory. The field metadata still reports the defaults. It reads them from the dataclass field records, not from the class attributes that were removed.
Inheritance
The decorator subtracts slots that base classes already provide, so a subclass does not redeclare them. Slotting a whole hierarchy therefore needs slots=True on every class.
from dataclasses import dataclass
@dataclass(slots=True)
class A:
a: int
@dataclass(slots=True)
class B(A):
b: int
print(A.__slots__, B.__slots__)
print(hasattr(B(1, 2), "__dict__"))
@dataclass
class Plain:
p: int
@dataclass(slots=True)
class C(Plain):
c: int
print(hasattr(C(1, 2), "__dict__"))B.__slots__ is ('b',) only, since a comes from A. B has no __dict__. C still has one because Plain is not slotted, so every C instance inherits a __dict__ from it. This is the same leak you saw with ordinary slots. Slotting a subclass of an unslotted base saves little, because most of the cost is already paid.
Gotchas caused by the replaced class
Because the decorator returns a different class object, anything that captured the original class now holds a stale reference.
Registries and earlier decorators
from dataclasses import dataclass
registry = []
def register(cls):
registry.append(cls)
return cls
@dataclass(slots=True)
@register
class Item:
name: str
print(registry[0] is Item)
print(isinstance(Item("hammer"), registry[0]))Decorators run bottom to top, so register sees the original class. The result is False for both lines, because Item now names the new class. Put register above @dataclass(slots=True) so it receives the final class.
Zero-argument super()
A method that calls super() with no arguments reads a hidden __class__ cell that points to the original class. On Python 3.10 through 3.13 that cell is not updated, so the check inside super() fails against instances of the new class. Python 3.14 fixed this.
from dataclasses import dataclass
@dataclass(slots=True)
class Base:
name: str
def describe(self):
return f"Base {self.name}"
@dataclass(slots=True)
class Child(Base):
extra: int = 0
def describe(self):
return super().describe() + f" +{self.extra}"
try:
print(Child("x", 2).describe())
except TypeError as exc:
print("TypeError:", exc)On 3.10 to 3.13 this prints a TypeError along the lines of super(type, obj): obj must be an instance or subtype of type. On 3.14 and later it prints Base x +2. On older versions, write super(Child, self) explicitly. That also fails, since Child now names the new class and the check passes, so it works but is verbose. Alternatively, avoid super() in slotted dataclass methods.
Class-creation hooks
Creating the second class runs type.__new__ again. Hooks that fire on class creation, such as __init_subclass__ on a base or a metaclass __new__, can run twice for one class statement. Make such hooks idempotent.
Weak references
Slotted classes do not support weak references unless __weakref__ is a slot. In a dataclass you cannot list __weakref__ yourself, because you cannot write __slots__. Python 3.11 added weakref_slot=True for this:
import weakref
from dataclasses import dataclass
@dataclass(slots=True, weakref_slot=True)
class Node:
value: int
n = Node(5)
ref = weakref.ref(n)
print(ref() is n)weakref_slot=True requires slots=True, and it needs Python 3.11 or later. Without it, weakref.ref(Node(5)) raises TypeError: cannot create weak reference to 'Node' object.
Frozen, pickling and copying
A frozen dataclass blocks __setattr__. Default unpickling of slotted objects restores state by setting attributes, which the frozen class would reject. For frozen=True, slots=True, the decorator adds __getstate__ and __setstate__ that bypass the block, so pickling and copying work.
import copy
import pickle
from dataclasses import dataclass, replace
@dataclass(frozen=True, slots=True)
class Pt:
x: int
y: int = 0
p = Pt(1, 2)
q = pickle.loads(pickle.dumps(p))
print(q == p)
print(copy.copy(p) == p)
print(replace(p, y=9))All three operations succeed. replace builds a new instance by calling __init__, so it never touches the frozen check. Define classes at module level if you plan to pickle them, because pickle finds a class by its qualified name.
Features that need a __dict__
Some tools assume every instance has a __dict__. The common case is functools.cached_property, which stores its result there:
from dataclasses import dataclass
from functools import cached_property
@dataclass(slots=True)
class Circle:
r: float
@cached_property
def area(self):
return 3.14159 * self.r ** 2
try:
Circle(2).area
except TypeError as exc:
print("TypeError:", exc)The error says there is no __dict__ to cache the property in. Use a plain @property, which recomputes each time. For an expensive calculation, add a field with field(init=False, default=None) and fill it in __post_init__ or on first use.
Choosing options
| Need | Setting | Python |
|---|---|---|
| No per-instance dict | `slots=True` | 3.10+ |
| Weak references | `slots=True, weakref_slot=True` | 3.11+ |
| Immutable and slotted | `frozen=True, slots=True` | 3.10+ |
| Keyword-only fields | `kw_only=True` | 3.10+ |
| Lazy cached values | Do not use slots, or use `@property` | any |
Measuring the effect
The savings are the same ones you measured earlier. A slotted dataclass drops the per-instance dict and stores values in fixed positions. Measure your own classes instead of assuming a figure.
import sys
from dataclasses import dataclass
@dataclass
class PlainPoint:
x: int
y: int
@dataclass(slots=True)
class SlottedPoint:
x: int
y: int
plain = PlainPoint(1, 2)
slotted = SlottedPoint(1, 2)
print("plain:", sys.getsizeof(plain) + sys.getsizeof(plain.__dict__))
print("slotted:", sys.getsizeof(slotted))The numbers vary with the Python version and implementation. The gap matters most when you create many instances, such as millions of small records. For a handful of objects it is irrelevant. Stored values such as the integers themselves are not part of this figure.
Checklist
- Confirm the Python version: 3.10 for
slots, 3.11 forweakref_slot. - Apply
slots=Trueto every class in a dataclass hierarchy, or the subclass regains a__dict__. - Put any class-registering decorator above
@dataclass(slots=True). - Replace
cached_propertywith@propertyor an explicit field. - Avoid zero-argument
super()before 3.14, or test it. - Read defaults with
fields(), not from class attributes.
Exercise
A slotted dataclass Order is declared with @dataclass(slots=True). A library registers it with a decorator placed below @dataclass(slots=True). Later, isinstance(Order(...), registered_class) returns False. Why, and what is the fix?
Show answer
The decorators run bottom to top, so the registration decorator receives the original class. dataclass(slots=True) then builds and returns a new class, and Order names that new class. The registry holds the discarded original, so isinstance against it fails. Move the registration decorator above @dataclass(slots=True) so it receives the final class.
Exercise
You write @dataclass(slots=True) class Config: debug: bool = False. What does Config.debug evaluate to, and how can you find the default value at runtime?
Show answer
Config.debug is a member descriptor (type member_descriptor), not False, because the decorator removes the default from the class namespace and stores it in the generated __init__. Read the default with dataclasses.fields(Config): the default attribute of the debug field is False. Calling Config().debug also returns False.
Exercise
A subclass is declared @dataclass(slots=True) class C(Plain) where Plain is an ordinary @dataclass. Does C instance have a __dict__, and why?
Show answer
Yes. Plain has no __slots__, so its instances get a __dict__, and C inherits that. Slots on C only add fixed storage and do not remove the inherited dict. To get no __dict__, every class in the hierarchy must be slotted, so Plain needs slots=True too.