21. Dataclasses, enums and slots — Cheat sheet
The essentials of module 21 on one page. Every runnable block on this page is checked against its output.
Quick lookup
Section titled “Quick lookup”| I want to… | Use… | Example |
|---|---|---|
| write a record class without boilerplate | @dataclass |
@dataclass class FitReport: model: str |
| give a field a default | name: type = value |
epochs: int = 100 |
| give each instance its own list or dict | field(default_factory=list) |
tags: list[str] = field(default_factory=list) |
| validate the values | def __post_init__(self): |
if self.lr <= 0: raise ValueError(...) |
| compute a field from other fields | field(init=False) + __post_init__ |
revenue: float = field(init=False) |
| make instances read-only and hashable | @dataclass(frozen=True) |
a split, a config, a version |
set a field inside a frozen __post_init__ |
object.__setattr__(self, name, value) |
object.__setattr__(self, "n", 3) |
| sort instances | @dataclass(order=True) |
fields compared as a tuple, in class order |
leave a field out of == and sorting |
field(compare=False) |
model: str = field(compare=False) |
| hide a field from the repr | field(repr=False) |
api_key: str = field(repr=False) |
| forbid new attributes, save memory | @dataclass(slots=True) |
typos raise AttributeError |
| force keyword arguments | @dataclass(kw_only=True), KW_ONLY, field(kw_only=True) |
KNNConfig(n_neighbors=15) |
| copy with changes (also frozen) | dataclasses.replace(obj, **changes) |
replace(cfg, lr=0.1) |
| convert to dict / tuple (recursive) | asdict(obj), astuple(obj) |
json.dumps(asdict(cfg)) |
| list the fields | dataclasses.fields(obj_or_cls) |
[f.name for f in fields(cfg)] |
| print a long dataclass readably | pprint.pprint(obj) |
one field per line |
| name a fixed set of choices | class Distance(Enum) |
Distance.EUCLIDEAN |
| choose values automatically | auto() |
StrEnum: lowercase name; Enum/IntEnum: 1, 2, 3 |
| members that are real strings | StrEnum |
Plan.BASIC == "basic" |
| members that are ordered ints | IntEnum |
Condition.GOOD > Condition.FAIR |
| combine on/off options | Flag |
Check.NULLS | Check.RANGE |
| look up a member by value | Distance("manhattan") |
ValueError if unknown |
| look up a member by name | Distance["MANHATTAN"] |
KeyError if unknown |
| test a value (3.12+) | "manhattan" in Distance |
True |
| list all members | list(Distance), for d in Distance |
definition order |
| branch on a member | match m: case Distance.EUCLIDEAN: |
dotted value pattern |
| forbid duplicate values | @enum.unique |
ValueError at class creation |
| a tuple with field names | class Neighbor(NamedTuple) |
n.distance, i, d, label = n |
| a copy of a named tuple with a change | n._replace(label=0) |
|
| fixed attributes in a plain class | __slots__ = ("x", "y") |
no __dict__ |
| measure the memory of many objects | tracemalloc |
bytes between start() and get_traced_memory() |
@dataclass parameters
Section titled “@dataclass parameters”| Parameter | Default | Effect |
|---|---|---|
init |
True |
generate __init__ |
repr |
True |
generate __repr__ (fields with repr=True) |
eq |
True |
generate __eq__ (fields with compare=True, as a tuple) |
order |
False |
generate __lt__, __le__, __gt__, __ge__; needs eq=True |
frozen |
False |
assignment and deletion raise FrozenInstanceError; generates __hash__ |
unsafe_hash |
False |
generate __hash__ even when not frozen |
match_args |
True |
generate __match_args__ for positional class patterns |
kw_only |
False |
every field of this class is keyword-only |
slots |
False |
generate __slots__ (a new class is created) |
weakref_slot |
False |
add a __weakref__ slot (with slots=True); advanced, not used in this module |
A method that the class defines itself, such as __repr__ or __str__, is kept. @dataclass only adds what is missing (except with order=True, which raises TypeError if you also define __lt__).
| Options | __eq__ |
__hash__ |
Set member / dict key |
|---|---|---|---|
@dataclass |
by fields | None |
no |
frozen=True |
by fields | by fields | yes |
eq=False |
identity | identity | yes (by identity) |
unsafe_hash=True |
by fields | by fields | yes, if you never change the fields |
field() options
Section titled “field() options”| Argument | Default | Effect |
|---|---|---|
default |
none | default value |
default_factory |
none | zero-argument callable called for each new instance |
init |
True |
parameter of __init__ |
repr |
True |
shown by __repr__ |
compare |
True |
used by __eq__ and the order methods |
hash |
None |
None: follows compare; False: not hashed |
kw_only |
MISSING |
True: keyword-only parameter |
metadata |
None |
read-only mapping for your own tools |
Dataclass recipes
Section titled “Dataclass recipes”from dataclasses import KW_ONLY, InitVar, asdict, astuple, dataclass, fieldfrom dataclasses import fields, replacefrom typing import ClassVar
@dataclass(frozen=True)class TrainConfig: learning_rate: float = 0.01 epochs: int = 100 tags: tuple[str, ...] = () # immutable default: no factory needed run_name: str = field(init=False) # derived METRICS: ClassVar[tuple[str, ...]] = ("r2", "rmse") # class constant, not a field
def __post_init__(self) -> None: if self.learning_rate <= 0: raise ValueError(f"learning_rate must be > 0, got {self.learning_rate}") object.__setattr__(self, "run_name", f"lr{self.learning_rate}-ep{self.epochs}")
cfg = TrainConfig(epochs=20)print(cfg)print(replace(cfg, learning_rate=0.1).run_name) # __post_init__ runs againprint(asdict(cfg))print(astuple(cfg))print([f.name for f in fields(cfg)], TrainConfig.METRICS)TrainConfig(learning_rate=0.01, epochs=20, tags=(), run_name='lr0.01-ep20')lr0.1-ep20{'learning_rate': 0.01, 'epochs': 20, 'tags': (), 'run_name': 'lr0.01-ep20'}(0.01, 20, (), 'lr0.01-ep20')['learning_rate', 'epochs', 'tags', 'run_name'] ('r2', 'rmse')@dataclass(frozen=True, order=True)class ModelScore: rank_key: float = field(init=False, repr=False) # the only compared field model: str = field(compare=False) rmse: float = field(compare=False)
def __post_init__(self) -> None: object.__setattr__(self, "rank_key", -self.rmse) # lower RMSE ranks higher
scores = [ModelScore("median", 358_737.4), ModelScore("linear", 223_691.3)]print(max(scores).model, [s.model for s in sorted(scores, reverse=True)])
@dataclassclass RunConfig: model: str _: KW_ONLY # every field below is keyword-only seed: int = 42 verbose: bool = False
@dataclass(kw_only=True)class CVRunConfig(RunConfig): n_folds: int # required field after defaults: fine when keyword-only
print(CVRunConfig("knn", n_folds=5))
@dataclassclass Sampler: seed: InitVar[int] # an __init__ argument passed to __post_init__, not stored first_draw: int = field(init=False)
def __post_init__(self, seed: int) -> None: self.first_draw = (seed * 1103515245 + 12345) % 2**31
print(Sampler(42), [f.name for f in fields(Sampler)])linear ['linear', 'median']CVRunConfig(model='knn', seed=42, verbose=False, n_folds=5)Sampler(first_draw=1250496027) ['first_draw']@dataclass(slots=True, frozen=True)class Reading: sensor_id: str temperature_c: float | None
r = Reading("S1", 20.21)print(r, Reading.__slots__, hasattr(r, "__dict__"))match r: case Reading(sensor_id, None): print(sensor_id, "has no value") case Reading(sensor_id, t) if t > 30: print(sensor_id, "is hot") case Reading(sensor_id=sid): print(sid, "is normal")Reading(sensor_id='S1', temperature_c=20.21) ('sensor_id', 'temperature_c') FalseS1 is normalEnum recipes
Section titled “Enum recipes”import jsonfrom enum import Enum, Flag, IntEnum, StrEnum, auto
class Distance(Enum): EUCLIDEAN = "euclidean" MANHATTAN = "manhattan"
d = Distance("manhattan") # by valueprint(d, repr(d), d.name, d.value, Distance["EUCLIDEAN"] is Distance.EUCLIDEAN)print([m.value for m in Distance], len(Distance), "euclidean" in Distance)print(json.dumps({"distance": d.value})) # a plain Enum member itself is not JSON
class Plan(StrEnum): BASIC = auto() STANDARD = auto() PREMIUM = auto()
@classmethod def _missing_(cls, value: object) -> "Plan | None": if isinstance(value, str): # called when the normal lookup fails return next((m for m in cls if m.value == value.strip().lower()), None) return None
print(Plan(" Premium "), Plan.BASIC == "basic", json.dumps([Plan.BASIC]))
class Severity(IntEnum): OK = 0 WARN = 1 FAIL = 2
print(max(Severity.WARN, Severity.OK).name, Severity.FAIL >= 2, Severity(1).name)
class Check(Flag): NULLS = auto() RANGE = auto() DUPLICATES = auto()
enabled = Check.NULLS | Check.RANGEprint(enabled, Check.RANGE in enabled, Check.DUPLICATES in enabled)Distance.MANHATTAN <Distance.MANHATTAN: 'manhattan'> MANHATTAN manhattan True['euclidean', 'manhattan'] 2 True{"distance": "manhattan"}premium True ["basic"]WARN True WARNCheck.NULLS|RANGE True FalseEnum |
StrEnum |
IntEnum |
Flag |
|
|---|---|---|---|---|
| Member is a | member only | str |
int |
member, combinable with | |
member == value |
False |
True |
True |
False |
< between members |
TypeError |
as strings | as ints | TypeError |
str(member) / f-string |
Distance.EUCLIDEAN |
euclidean |
4 |
Check.NULLS |
json.dumps(member) |
TypeError |
value | value | TypeError |
auto() |
1, 2, 3 | lowercase name | 1, 2, 3 | 1, 2, 4, 8 |
| Standard-library examples | uuid.SafeUUID |
http.HTTPMethod (3.11+) |
http.HTTPStatus, inspect.Parameter.kind |
re.RegexFlag (an IntFlag) |
Enum members: .name, .value; class: Cls.__members__ (name → member, aliases included), len(Cls), iteration (aliases skipped). A second name with an existing value is an alias. Members are singletons: compare with is.
def describe(metric: Distance) -> str: match metric: case Distance.EUCLIDEAN: # dotted name: a value pattern (==) return "straight line" case Distance.MANHATTAN: return "city blocks" case _: # a forgotten member fails loudly raise ValueError(f"unhandled {metric!r}")
print([describe(m) for m in Distance])['straight line', 'city blocks']NamedTuple
Section titled “NamedTuple”from collections import namedtuplefrom typing import NamedTuple
class Neighbor(NamedTuple): index: int distance: float label: int = 0 # defaults come last
n = Neighbor(17, 2.236, 1)i, dist, label = n # unpacks like a tupleprint(n.distance, n[1], n._asdict(), n._replace(label=0))print(Neighbor._fields, Neighbor._field_defaults, Neighbor._make([3, 0.5, 1]))print(n == (17, 2.236, 1), sorted([Neighbor(2, 0.1), Neighbor(1, 0.9)])[0].index)
Point = namedtuple("Point", ["x", "y"], defaults=[0.0]) # functional formprint(Point(1.5), Point._fields)2.236 2.236 {'index': 17, 'distance': 2.236, 'label': 1} Neighbor(index=17, distance=2.236, label=0)('index', 'distance', 'label') {'label': 0} Neighbor(index=3, distance=0.5, label=1)True 1Point(x=1.5, y=0.0) ('x', 'y')collections.namedtuple |
typing.NamedTuple |
@dataclass(frozen=True) |
TypedDict |
|
|---|---|---|---|---|
| Type hints | no | yes | yes | yes |
| Immutable | yes | yes | yes (shallow) | no |
| Unpacks, indexes | yes | yes | no | no (a dict) |
| Equals a plain tuple / dict | yes | yes | no | yes (it is a dict) |
| Validation hook | no | no | __post_init__ |
no (type checker only) |
| Methods and properties | yes | yes | yes | no |
slots and memory
Section titled “slots and memory”import sysimport tracemalloc
class Plain: def __init__(self, x: float, y: float) -> None: self.x, self.y = x, y
class Slotted: __slots__ = ("x", "y") # no __dict__; a class attribute named x would be an error
def __init__(self, x: float, y: float) -> None: self.x, self.y = x, y
def bytes_per_object(cls: type, n: int = 10_000) -> float: values = [float(i) for i in range(n)] # created before the measurement tracemalloc.start() objects = [cls(v, v) for v in values] used, _peak = tracemalloc.get_traced_memory() tracemalloc.stop() return used / len(objects)
print(sys.getsizeof(Plain(1.0, 2.0)), sys.getsizeof(Slotted(1.0, 2.0))) # shallowprint(round(bytes_per_object(Plain)), round(bytes_per_object(Slotted))) # with the list48 4897 57| Rule | Detail |
|---|---|
no __dict__ |
no new attributes, no vars(obj) |
| unset slot | reading it raises AttributeError |
| class attribute with a slot’s name | ValueError: 'x' in __slots__ conflicts with class variable |
subclass without __slots__ |
gets a __dict__ again |
subclass with __slots__ |
lists only its new names |
@dataclass(slots=True) |
handles defaults; on 3.12–3.13, zero-argument super() in its methods fails |
sys.getsizeof |
shallow: misses the attribute storage of plain instances and all referenced objects |
| CPython 3.11+ | plain instances store attributes compactly; measure before you optimize |
Which record type?
Section titled “Which record type?”| Need | Use |
|---|---|
| quick script, unknown keys | dict |
| type hints for JSON dicts passed on unchanged | TypedDict |
| tuple-like result that callers unpack | NamedTuple |
| a record with defaults, validation, methods | @dataclass |
| a value that must not change, a dict key | @dataclass(frozen=True) |
| millions of small objects | @dataclass(slots=True) or __slots__ |
| behavior and changing state (an estimator) | plain class |
| untrusted input that must be validated and converted | pydantic model (module 44) |
| a fixed set of named options | Enum / StrEnum / IntEnum |
Gotchas
Section titled “Gotchas”x: list = []in a dataclass raisesValueError: mutable default ... use default_factory. Any unhashable default is rejected, including an instance of a non-frozen dataclass.- Fields without defaults must come first:
TypeError: non-default argument 'b' follows default argument 'a'. Fix with keyword-only fields. - Annotations name the fields; they are not checked at run time.
- A name without an annotation is a plain class attribute, not a field. A
ClassVarannotation is not a field either. __post_init__runs only in__init__(and inreplace()), not on later assignments.frozen=Trueis shallow: a list field still changes, andhash()fails anyway because a list is unhashable. Store tuples.compare=Falseremoves a field from==and the hash too, not only from sorting.- With
order=True, the field order is the sort order. asdict()keeps enum members as members:json.dumps()then fails for a plainEnum. UseStrEnumor convert.value.asdict()deep-copies;replace()does not: the copy shares lists and dicts with the original.- A plain
Enummember is not equal to its value.IntEnumandStrEnummembers are, which can hide mix-ups. print()of anIntEnumshows the number (4), of aStrEnumthe value (premium). Use.namefor the name.auto()in aStrEnumgives the lowercase name, not the text in your file (month_to_monthvsmonth-to-month).case EUCLIDEAN:is a capture pattern. Writecase Distance.EUCLIDEAN:.- A
NamedTuplesorts by its first field and equals a plain tuple with the same items. __slots__does not freeze values; combineslots=Truewithfrozen=Truefor that.