Sub topic 12
slots=True and kw_only for modern dataclasses
This chapter assumes you can write a basic @dataclass, you know what __init__ and __repr__ do, and you are on Python 3.10 or newer. Both options below were added to @dataclass in 3.10.
Why two more options
A plain dataclass instance stores its attributes in a per-instance dictionary called __dict__. That is flexible, but it costs memory and lets you add attributes by accident. Another problem shows up when a class has many fields: positional construction such as Config("localhost", 8080, True, False) is easy to get wrong.
slots=True addresses the first problem. kw_only=True addresses the second.
slots=True
A class that defines __slots__ stores its attributes in fixed slots instead of a __dict__. Each instance is smaller, and attribute access is slightly faster. With slots=True, the decorator builds the __slots__ tuple from your fields, so you don't write it by hand.
from dataclasses import dataclass
@dataclass(slots=True)
class Point:
x: float
y: float = 0.0
p = Point(1.0, 2.0)
print(Point.__slots__) # ('x', 'y')
print(hasattr(p, "__dict__")) # False
try:
p.z = 3.0
except AttributeError as e:
print("blocked:", e)Because there is no __dict__, assigning an attribute that is not a field raises AttributeError. This catches typos such as p.xx = 5.
How it works and what to watch for
The __slots__ entry must exist when a class is created. So the decorator cannot modify your class in place. It builds a new class with the slots and returns that one. Three consequences follow:
- Code that holds a reference to the original class before decoration sees a different object. This is rarely a problem for normal use.
- Zero-argument
super()inside methods can fail on older Python versions. It works on current releases, butsuper(Point, self)style calls that name the class explicitly are the ones to check. - A field default is not stored as a class attribute, because that would clash with the slot of the same name. The decorator handles this for you, but hand-written code that reads
Point.yas a default will not work.
Slots also change two other behaviors. Instances cannot be weakly referenced unless you add weakref_slot=True (3.11 and newer). The __dict__-based cached_property decorator does not work, because it needs somewhere to store its value.
kw_only=True
With kw_only=True, every field must be passed by keyword. Positional arguments are rejected.
from dataclasses import dataclass
@dataclass(kw_only=True)
class Server:
host: str
port: int = 8080
debug: bool = False
print(Server(host="localhost", debug=True))
try:
Server("localhost", 80)
except TypeError as e:
print("error:", e)Keyword-only fields also remove an ordering restriction. Normally a field without a default cannot follow one that has a default. Keyword-only fields are exempt, because argument order no longer matters for them.
from dataclasses import dataclass
@dataclass(kw_only=True)
class Job:
retries: int = 3
name: str # allowed: no default after a default
print(Job(name="backup"))This is especially useful with inheritance, where a subclass often wants to add a required field after the parent's defaulted ones.
Marking only some fields
You can set kw_only on a single field, or place the KW_ONLY marker in the class body. Every field after the marker is keyword-only.
from dataclasses import dataclass, field, KW_ONLY
@dataclass
class Request:
url: str
_: KW_ONLY
timeout: float = 5.0
retries: int = field(default=3)
print(Request("https://example.com", timeout=2.0))Here url can still be passed by position. timeout and retries must use names. The name _ is a convention. The marker is not stored as a field.
Combining both
The options are independent, and you can use them together:
from dataclasses import dataclass
@dataclass(slots=True, kw_only=True)
class Config:
host: str
port: int = 8080
cfg = Config(host="localhost")
print(cfg) # Config(host='localhost', port=8080)| Option | Effect | Main benefit | Main cost |
|---|---|---|---|
| `slots=True` | No `__dict__`, fixed attributes | Less memory, typo protection | No dynamic attributes, a new class is built |
| `kw_only=True` | All fields passed by name | Readable calls, flexible ordering | Callers must type field names |
Common errors
- Using either option on Python 3.9 or older raises
TypeError: dataclass() got an unexpected keyword argument. - Setting an undeclared attribute on a slotted instance raises
AttributeError. - Calling a
kw_onlyclass positionally raisesTypeErrorabout positional arguments.
Exercise
A dataclass is declared with @dataclass(slots=True) and has fields name: str and age: int. What happens when you run person.nickname = "Bo" on an instance, and which option would you change to allow it?
Show answer
It raises AttributeError, because a slotted instance has no __dict__ and nickname is not a declared field. You can either add nickname as a field, or remove slots=True so the instance gets a __dict__.
Exercise
You want Job to have a defaulted field retries: int = 3 followed by a required field name: str. Which dataclass option makes this legal, and how is the required field then passed?
Show answer
Use kw_only=True (or mark those fields keyword-only with KW_ONLY). The fields are then passed by keyword, for example Job(name="backup").