Sub topic 12
slots=True and kw_only for modern dataclasses
This chapter covers two options added in Python 3.10: slots=True, which changes how instances store their attributes, and kw_only=True, which changes how the generated __init__ accepts arguments. It assumes you know how @dataclass generates __init__, how field() and default_factory work, and how dataclass inheritance orders fields. You need Python 3.10 or newer to run the examples.
What slots=True changes
A normal instance keeps its attributes in a per-instance dictionary called __dict__. That dictionary is flexible: you can add any attribute at any time. It also costs memory, and it hides typos, because a misspelled assignment silently creates a new attribute.
A class that defines __slots__ replaces the dictionary with a fixed set of attribute slots. Python allocates space for exactly those names and nothing else. @dataclass(slots=True) writes the __slots__ tuple for you from the field list.
import sys
from dataclasses import dataclass
@dataclass
class PlainPoint:
x: float
y: float
@dataclass(slots=True)
class SlotPoint:
x: float
y: float
plain = PlainPoint(1.0, 2.0)
slotted = SlotPoint(1.0, 2.0)
print(hasattr(plain, "__dict__")) # True
print(hasattr(slotted, "__dict__")) # False
print(SlotPoint.__slots__) # ('x', 'y')
plain_size = sys.getsizeof(plain) + sys.getsizeof(plain.__dict__)
slot_size = sys.getsizeof(slotted)
print(plain_size > slot_size) # True on CPython
try:
slotted.z = 3
except AttributeError as exc:
print("rejected:", exc)Two benefits follow from this. Each instance is smaller, which matters when you create hundreds of thousands of them. Attribute access is also slightly faster. Assigning to an attribute that is not a field raises AttributeError, which catches typos such as slotted.xx = 5.
The size benefit depends on the Python version. Recent CPython releases store instance attributes compactly even without slots, so the gap is smaller than it was in older versions. Measure with your own data before treating slots=True as a memory fix.
Why the decorator rebuilds the class
You might ask why you cannot just write __slots__ by hand in a dataclass. The reason is defaults. A default value such as port: int = 8080 is stored as a class attribute, and a slot with the same name conflicts with that class attribute.
try:
class Broken:
__slots__ = ("port",)
port = 8080
except ValueError as exc:
print(exc) # 'port' in __slots__ conflicts with class variableslots=True avoids this by building a second class. The decorator collects the fields and defaults, creates a new class with __slots__ set and the default class attributes removed, and returns that new class. The generated __init__ supplies the defaults at construction time instead.
This has consequences:
- The name you see after decoration refers to a different class object than the one Python first created from your
classstatement. Code that grabbed a reference to the original class during its body, such as a decorator that registers the class, sees the old one. - In Python versions before 3.14, a method that calls zero-argument
super()fails with aTypeError. The method's hidden class reference still points to the discarded original class. Writesuper(MyClass, self)in such methods, or avoidslots=Trueon those classes. functools.cached_propertydoes not work, because it stores its result in__dict__, which no longer exists.
Slots and inheritance
A subclass only gets slots if it asks for them. If a subclass does not define __slots__, Python gives its instances a __dict__ again, and the memory savings are gone.
from dataclasses import dataclass
@dataclass(slots=True)
class Base:
a: int
@dataclass
class Loose(Base):
b: int
@dataclass(slots=True)
class Tight(Base):
b: int
print(hasattr(Loose(1, 2), "__dict__")) # True
print(hasattr(Tight(1, 2), "__dict__")) # False
print(Tight.__slots__) # ('b',)The __slots__ of Tight lists only b. Slot a is already provided by Base, and the dataclass machinery leaves inherited names out so they are not duplicated.
Other limits to know:
- Weak references stop working by default, because the
__weakref__slot is not created. On Python 3.11 or newer, passweakref_slot=Truealong withslots=Trueif you needweakref.ref(obj). - Multiple inheritance from two classes that both define non-empty
__slots__raises aTypeErrorabout instance lay-out conflict. - Assigning a class-level default after the fact does not work as it does on a normal class, because the class attribute for the field no longer exists.
What kw_only=True changes
By default the generated __init__ accepts fields positionally. Positional arguments are easy to get wrong when a class has many fields of the same type. With kw_only=True, every field of that class must be passed by keyword.
from dataclasses import dataclass
@dataclass(kw_only=True)
class Connection:
host: str
port: int = 5432
use_tls: bool = True
conn = Connection(host="db.internal", use_tls=False)
print(conn) # Connection(host='db.internal', port=5432, use_tls=False)
try:
Connection("db.internal")
except TypeError as exc:
print("rejected:", exc)Call sites such as Connection(host="db.internal", use_tls=False) document themselves. Reordering fields in the class later does not break existing callers, because no caller depends on position.
Mixing positional and keyword-only fields
You do not have to make a whole class keyword-only. There are two finer-grained tools.
The first is field(kw_only=True) on a single field. The second is the KW_ONLY sentinel: a pseudo-field written as _: KW_ONLY. Every field after it is keyword-only. The sentinel itself is not a field and does not appear in fields().
from dataclasses import dataclass, KW_ONLY, field, fields
@dataclass
class Job:
name: str
retries: int = 3
_: KW_ONLY
queue: str
verbose: bool = False
@dataclass
class Job2:
name: str
retries: int = 3
queue: str = field(kw_only=True)
verbose: bool = field(default=False, kw_only=True)
print(Job("backup", queue="nightly"))
# Job(name='backup', retries=3, queue='nightly', verbose=False)
print([f.name for f in fields(Job)])
# ['name', 'retries', 'queue', 'verbose']Notice that queue has no default but comes after retries, which does. In a normal dataclass this raises TypeError: non-default argument 'queue' follows default argument. Keyword-only fields escape that rule, because Python does not care about default order among keyword-only parameters.
The generated __init__ moves keyword-only fields to the end of its parameter list, after all positional ones. The repr, comparisons and fields() still follow the order in which you declared the fields.
Keyword-only fields are also left out of __match_args__, the tuple that positional patterns in a match statement use. A case Job(name, retries) pattern can bind only positional fields.
kw_only and inheritance
The most practical use of kw_only is to fix the inheritance problem from the previous chapter. A base class with a defaulted field blocks any required field in a subclass. Making the subclass's fields keyword-only removes the conflict.
from dataclasses import dataclass, field
@dataclass
class Animal:
name: str
sound: str = "..."
@dataclass(kw_only=True)
class Dog(Animal):
tricks: list[str]
age: int = field(default=1)
rex = Dog("Rex", tricks=["sit"])
print(rex) # Dog(name='Rex', sound='...', tricks=['sit'], age=1)The kw_only=True argument applies only to fields declared in that class body. The inherited name and sound stay positional, which is why Dog("Rex", ...) still works. A keyword-only base class does the opposite: its fields remain keyword-only in every subclass.
Using both together
The two options are independent, and you can combine them in the same call.
from dataclasses import dataclass
@dataclass(slots=True, kw_only=True, frozen=True)
class Settings:
host: str
port: int = 8080
debug: bool = False
s = Settings(host="localhost")
print(s) # Settings(host='localhost', port=8080, debug=False)
print(hash(s) == hash(Settings(host="localhost"))) # TrueThis combination suits configuration objects: compact, hashable, protected against attribute typos, and unambiguous at every call site.
| Option | Minimum Python | Effect | Main cost |
|---|---|---|---|
| `slots=True` | 3.10 | Fixed attribute storage, no `__dict__` | New class object, no `cached_property`, no weak references by default |
| `weakref_slot=True` | 3.11 | Adds a `__weakref__` slot to a slotted class | Slightly larger instances |
| `kw_only=True` | 3.10 | All fields of this class are keyword-only | Callers cannot pass positional arguments |
| `field(kw_only=True)` | 3.10 | One field is keyword-only | Mixed signature to read |
| `KW_ONLY` sentinel | 3.10 | Fields after `_: KW_ONLY` are keyword-only | The `_` name is reserved in the class body |
Choosing the options
Common errors
- Adding an attribute in
__post_init__. Withslots=True, assigningself.total = ...for a name that is not a declared field raisesAttributeError. Declare it astotal: float = field(init=False)instead. - Expecting a class-level default to stay visible. On a slotted dataclass,
Config.portis a slot descriptor, not8080. Read defaults fromfields(Config). - Forgetting that subclasses need their own
slots=True. A plain@dataclasssubclass quietly brings back__dict__. - Passing positional arguments to a keyword-only class. The
TypeErrorappears at the call site. Update callers, or move only the risky fields behindKW_ONLY. - Using
_as a real field name next toKW_ONLY. Only one sentinel named_is expected. Use one_: KW_ONLYline per class body.
Exercise
A slotted dataclass Item has fields name: str and price: float. A method in __post_init__ runs self.discounted = self.price * 0.9, and discounted is not declared as a field. What happens when you create an Item, and how do you fix it while keeping slots=True?
Show answer
Creating an Item raises AttributeError, because the slotted class has no __dict__ and no slot named discounted. Declare the attribute as a field that is excluded from the constructor: discounted: float = field(init=False). Then __post_init__ can assign it, and it also appears in repr, fields() and comparisons unless you turn those off with repr=False or compare=False.
Exercise
Given @dataclass class Base: id: int; label: str = "none", write a subclass Tagged that adds a required tag: str field without raising a field-ordering error. How do you construct an instance, and which fields are positional?
Show answer
Use @dataclass(kw_only=True) class Tagged(Base): tag: str. Construct it with Tagged(1, tag="x") or Tagged(1, "other", tag="x"). Only the inherited id and label are positional, because kw_only=True applies just to fields declared in Tagged. Alternatively, write tag: str = field(kw_only=True) to mark that single field.