Sub topic 9
Slotted Dataclasses with slots=True
This chapter assumes you know how __slots__ removes the instance __dict__, why a class attribute with the same name as a slot raises ValueError, and the basics of @dataclass. It also assumes you know how slots behave under inheritance.
The problem: dataclass defaults meet slots
A dataclass is a class decorator that generates __init__, __repr__, and __eq__ from annotated fields. A field default such as y: int = 0 is normally stored as a class attribute named y.
That collides with slots. If you write __slots__ = ("x", "y") by hand and also give y a default, the class body defines a class variable with the same name as a slot. Python rejects it when the class is created:
class Bad:
__slots__ = ("x",)
x = 0Running this raises ValueError at class creation. Hand-written slots and dataclass defaults therefore don't work together.
The fix: `slots=True`
Python 3.10 added a slots argument to @dataclass. When you pass slots=True, the decorator builds a new class with __slots__ generated from the field names. It removes the default values from the class namespace first, so there is no conflict. It then uses those defaults when it generates __init__.
from dataclasses import dataclass
@dataclass(slots=True)
class Point:
x: int
y: int = 0
p = Point(1)
print(p)
print(hasattr(p, "__dict__"))This prints Point(x=1, y=0) and then False. The default for y still works, and the instance has no __dict__.
What the decorator really does
Ordinary @dataclass modifies the class you wrote and returns the same object. With slots=True, the __slots__ have to exist when the class is created, so the decorator can't add them afterward. It creates a second class with the same name, body, and bases, plus the generated __slots__, and returns that one.
The diagram below shows the sequence.
Two consequences follow from this replacement:
- The name
Pointrefers to the new class. The original class object is not the one you use. - Code that captured a reference to the original class before decoration, such as a zero-argument
super()call in a method, needs care. Zero-argumentsuper()relies on a hidden cell that points to the class. In Python 3.10 and 3.11 it can fail in slotted dataclasses, because the cell still refers to the discarded original. This was fixed in later releases. If you support older versions, use explicit arguments such assuper(Point, self), or avoidsuper()in those methods.
Behavior you can rely on
A slotted dataclass inherits the usual slot restrictions. You can't add attributes that aren't fields:
from dataclasses import dataclass
@dataclass(slots=True)
class Point:
x: int
y: int = 0
p = Point(1)
try:
p.z = 3
except AttributeError as exc:
print("AttributeError:", exc)The decorator also generates the methods you normally expect. repr, ==, and keyword construction all work as in a regular dataclass.
| Feature | `@dataclass` | `@dataclass(slots=True)` |
|---|---|---|
| Instance `__dict__` | Yes | No |
| Field defaults | Yes | Yes |
| Arbitrary new attributes | Allowed | `AttributeError` |
| Class object | Same one you wrote | A new class replaces it |
| Minimum Python | 3.7 | 3.10 |
Inheritance still matters
The decorator only generates slots for the fields declared in that class. If a slotted dataclass inherits from a plain class, or a subclass is a normal dataclass, instances have a __dict__ again, exactly as in the earlier chapter on inheritance. To keep the savings, apply slots=True at every level.
from dataclasses import dataclass
@dataclass(slots=True)
class Base:
a: int
@dataclass(slots=True)
class Child(Base):
b: int = 0
c = Child(1, 2)
print(c)
print(hasattr(c, "__dict__"))The Child class declares only b in its own slots. The field a stays in Base, so nothing is duplicated.
Other options
You can combine slots=True with frozen=True to get an immutable, dict-free record. If you need weak references, newer Python versions (3.11 and later) accept weakref_slot=True in the decorator, which adds the __weakref__ slot for you. On 3.10, you can't use that argument, so write the weak-reference slot out by hand, with the limits that implies for defaults.
Exercise
Exercise
A dataclass is declared as @dataclass(slots=True) with a field y: int = 0. Why does this work, when writing __slots__ = ("y",) together with y = 0 by hand raises ValueError?
Show answer
The decorator removes the default value from the class namespace before it creates the new class with the generated __slots__, so no class variable named y collides with the slot. It then uses the saved default when it generates __init__.
Exercise
You apply @dataclass(slots=True) to Child, which inherits from a plain class Base that has no __slots__. Does Child have an instance __dict__?
Show answer
Yes. The plain base class provides a __dict__ to every instance, so the savings are lost. Every class in the hierarchy needs slots.