Skip to content

21. Dataclasses, enums and slots

Many classes in a data project only hold data: a training configuration, a fit report, a train/test split, a model score, one sensor reading. In module 20 you wrote __init__, __repr__, __eq__ and __lt__ by hand for such classes. This module lets Python write them for you. You also replace “magic strings” such as "euclidean" with enumerations, turn neighbor lists into named tuples, and measure how much memory __slots__ saves on 8,064 sensor readings.

  • Write record classes with @dataclass, defaults, field(default_factory=...) and __post_init__ validation, and explain the mutable-default error that dataclasses prevent.
  • Choose the dataclass options frozen, order, slots and kw_only, and copy or convert instances with replace(), asdict(), astuple() and fields().
  • Name a fixed set of choices with Enum, StrEnum, IntEnum and auto(); look members up by value and by name, iterate over them and use them in match.
  • Build light, immutable records with typing.NamedTuple and collections.namedtuple, and know where their tuple behavior helps and where it hurts.
  • Use __slots__ to fix the attributes of a class, and measure the memory effect with sys.getsizeof and tracemalloc.
  • Choose between a dataclass, a NamedTuple, a TypedDict, a dict, a plain class and a pydantic model.

Why dataclasses: records without boilerplate

Section titled “Why dataclasses: records without boilerplate”

Boilerplate is code that you must write again and again with only small changes. A class that holds three values needs an __init__ that stores them, a __repr__ that shows them and an __eq__ that compares them. Here is a fit report written by hand, in the style of module 20:

class FitReportByHand:
def __init__(self, model: str, n_samples: int, train_score: float) -> None:
self.model = model
self.n_samples = n_samples
self.train_score = train_score
def __repr__(self) -> str:
return (
f"FitReportByHand(model={self.model!r}, n_samples={self.n_samples!r}, "
f"train_score={self.train_score!r})"
)
def __eq__(self, other: object) -> bool:
if not isinstance(other, FitReportByHand):
return NotImplemented
mine = (self.model, self.n_samples, self.train_score)
theirs = (other.model, other.n_samples, other.train_score)
return mine == theirs

Each field name appears 4 to 6 times. Add a field and you must change 4 places. Forget one, and == or the repr is silently wrong.

A data class is a class whose main job is to hold data. The decorator @dataclass from the dataclasses module reads the class annotations and writes the methods for you. Each annotated class variable becomes a field: a named value that every instance stores.

import inspect
from dataclasses import dataclass
@dataclass
class FitReport:
model: str
n_samples: int
train_score: float
report = FitReport("KNNClassifier(n_neighbors=5)", 3750, 0.842)
print(report)
print(report == FitReport("KNNClassifier(n_neighbors=5)", 3750, 0.842))
print(report.train_score)
print(inspect.signature(FitReport))
Output
FitReport(model='KNNClassifier(n_neighbors=5)', n_samples=3750, train_score=0.842)
True
0.842
(model: str, n_samples: int, train_score: float) -> None

Five lines replace twenty. The decorator generated an __init__ with one parameter per field, in the order of the class body, a __repr__ that shows every field, and an __eq__ that compares the fields as a tuple. @dataclass is a class decorator (module 11): it takes the class, adds the methods and returns the same class. The result is an ordinary class. You can add methods and properties to it.

flowchart LR
    A["class body:<br/>model: str<br/>n_samples: int<br/>train_score: float"] --> D["@dataclass"]
    D --> I["__init__(model, n_samples, train_score)"]
    D --> R["__repr__"]
    D --> E["__eq__"]
    D -.->|"order=True"| L["__lt__, __le__, __gt__, __ge__"]
    D -.->|"frozen=True"| H["__setattr__ blocked, __hash__"]

The annotations decide which names are fields. They are not checked when the code runs:

odd = FitReport("knn", "many", None)
print(odd)
Output
FitReport(model='knn', n_samples='many', train_score=None)

Python stores whatever you pass. A type checker such as mypy (module 12) flags this call before the code runs. A check in __post_init__ (below) stops it at run time.

A field with a value in the class body has a default. Fields without a default must come first, because the generated __init__ is a normal function, and a normal function cannot have a required parameter after an optional one:

@dataclass
class TrainConfig:
learning_rate: float = 0.01
epochs: int = 100
print(TrainConfig())
print(TrainConfig(epochs=20))
Output
TrainConfig(learning_rate=0.01, epochs=100)
TrainConfig(learning_rate=0.01, epochs=20)
@dataclass
class BadConfig:
learning_rate: float = 0.01
model: str
Output
TypeError: non-default argument 'model' follows default argument 'learning_rate'

Python raises the error when it creates the class, not when you call it. So you see the mistake as soon as the module loads.

Now the most important rule. Module 13 showed the mutable default argument gotcha: a list default is created once and shared by every call. A dataclass default would have the same bug, because the class body runs once. So @dataclass refuses a list, dict or set default:

@dataclass
class Experiment:
name: str
scores: list[float] = []
Output
ValueError: mutable default <class 'list'> for field scores is not allowed: use default_factory

The error names the fix. field() describes one field in detail. Its argument default_factory takes a function with no arguments. The generated __init__ calls it once for each new instance, so every instance gets its own list:

from dataclasses import field
@dataclass
class Experiment:
name: str
scores: list[float] = field(default_factory=list)
def log(self, score: float) -> None:
self.scores.append(score)
knn_5 = Experiment("knn-k5")
knn_15 = Experiment("knn-k15")
knn_5.log(0.81)
knn_5.log(0.83)
print(knn_5)
print(knn_15)
print(knn_5.scores is knn_15.scores)
Output
Experiment(name='knn-k5', scores=[0.81, 0.83])
Experiment(name='knn-k15', scores=[])
False

Any function with no arguments works as a factory: list, dict, set, Counter, or a lambda such as field(default_factory=lambda: ["r2", "rmse"]). The check is wider than lists: @dataclass rejects any default whose type is unhashable. That includes an instance of another non-frozen dataclass, which would be shared in the same way.

field() has more options. You need the first four often:

Argument Effect Typical use
default=0.5 a plain default value same as x: float = 0.5, needed when you also pass other options
default_factory=list call the factory for each new instance lists, dicts, sets, counters
init=False not a parameter of __init__ a value that __post_init__ computes
repr=False not shown by __repr__ long data, secrets such as an API key
compare=False ignored by == and by the order methods a timestamp, a comment, a cached value
kw_only=True keyword-only parameter of __init__ one optional setting at the end
hash=None None follows compare; False leaves it out of the hash rarely needed
metadata={"unit": "s"} a read-only dict for your own tools units, column descriptions

A class variable annotated with typing.ClassVar is not a field. It belongs to the class, as in module 18:

from typing import ClassVar
@dataclass
class Experiment:
name: str
scores: list[float] = field(default_factory=list)
MAX_RUNS: ClassVar[int] = 50 # shared constant, not a field
print(Experiment("knn-k5"), Experiment.MAX_RUNS)
Output
Experiment(name='knn-k5', scores=[]) 50

The generated __init__ only stores the values. If you define a method __post_init__(self), the generated __init__ calls it as its last step. Use it for two jobs: check the values and compute derived fields, fields whose value comes from other fields.

@dataclass
class TrainConfig:
learning_rate: float = 0.01
epochs: int = 100
test_size: float = 0.25
run_name: str = field(init=False) # computed, not passed in
def __post_init__(self) -> None:
if self.learning_rate <= 0:
raise ValueError(f"learning_rate must be > 0, got {self.learning_rate}")
if not 0 < self.test_size < 1:
raise ValueError(f"test_size must be in (0, 1), got {self.test_size}")
self.run_name = f"lr{self.learning_rate}-ep{self.epochs}"
print(TrainConfig(learning_rate=0.1))
Output
TrainConfig(learning_rate=0.1, epochs=100, test_size=0.25, run_name='lr0.1-ep100')

A bad value stops the object from being created:

TrainConfig(test_size=25) # a percentage instead of a fraction
Output
ValueError: test_size must be in (0, 1), got 25

A configuration or another value object should check its values when it is created, so that no invalid object can exist. Estimators follow a different convention, which module 19 taught: __init__ stores the parameters unchanged and fit() validates them, so that set_params() and cloning stay simple. Use __post_init__ checks for data containers, not for estimators. __post_init__ runs only once, in __init__. A later assignment such as config.test_size = 25 is not checked, and run_name goes stale when epochs changes. A frozen dataclass closes this gap.

@dataclass(frozen=True) makes instances read-only after __init__. An assignment raises dataclasses.FrozenInstanceError, a subclass of AttributeError. A value object is an object defined only by its values, such as a date, an amount of money or a train/test split. Two value objects with the same values are interchangeable, and nobody should change one in place.

@dataclass(frozen=True)
class Split:
train: tuple[int, ...]
test: tuple[int, ...]
split = Split(train=(0, 1, 2, 4, 5, 7), test=(3, 6))
print(split, hash(split) == hash(Split((0, 1, 2, 4, 5, 7), (3, 6))))
Output
Split(train=(0, 1, 2, 4, 5, 7), test=(3, 6)) True
split.test = (0, 1)
Output
dataclasses.FrozenInstanceError: cannot assign to field 'test'

A frozen dataclass also gets a __hash__ built from its fields. So you can use it as a dict key or a set member, for example to cache the score of a model on one split. To change a value, you make a new object with dataclasses.replace() (below).

Frozen is shallow: it blocks assignment to the fields, not changes inside them. A list field can still grow with .append(). And hash() fails anyway, even before any change, because a list is unhashable. Store sequences as tuples in a frozen dataclass. Example 2 shows the trap.

Inside __post_init__ of a frozen class, self.x = ... raises too. To set a derived field there, call object.__setattr__(self, "x", value). This bypasses the block on purpose, once, while the object is being built.

@dataclass(order=True) adds __lt__, __le__, __gt__ and __ge__. They compare the fields as a tuple, in the order of the class body, as (a.f1, a.f2) < (b.f1, b.f2). The field order is the sort order. A model registry that sorts model versions is a typical use, also outside data science:

@dataclass(frozen=True, order=True)
class ModelVersion:
major: int
minor: int
patch: int
def __str__(self) -> str:
return f"{self.major}.{self.minor}.{self.patch}"
versions = [ModelVersion(1, 10, 0), ModelVersion(1, 2, 3), ModelVersion(0, 9, 12)]
print([str(v) for v in sorted(versions)])
print(max(versions), ModelVersion(1, 2, 3) < ModelVersion(1, 10, 0))
print(sorted(["1.10.0", "1.2.3", "0.9.12"]))
Output
['0.9.12', '1.2.3', '1.10.0']
1.10.0 True
['0.9.12', '1.10.0', '1.2.3']

The dataclass compares numbers: minor version 10 is greater than 2. The strings compare character by character, and "1.10.0" sorts before "1.2.3". A field with compare=False is left out of the comparison, and also out of ==.

eq and frozen together decide __hash__:

Options __eq__ __hash__ Use in a set or as a dict key
@dataclass (eq=True is the default) compares fields set to None no: TypeError: unhashable type
@dataclass(frozen=True) compares fields from the fields yes
@dataclass(eq=False) identity (inherited from object) identity yes, by identity
@dataclass(unsafe_hash=True) compares fields from the fields yes, but you promise not to change the fields

The first row follows the rule of module 20: a class that defines __eq__ without __hash__ is unhashable. A mutable object that hashes by its values gets lost in a set when a value changes.

@dataclass(slots=True) adds a __slots__ attribute to the class. Instances then have a fixed set of attributes and no per-instance __dict__ (see __slots__ below). They use less memory, and an assignment to a misspelled attribute raises an error instead of creating a new attribute.

@dataclass(kw_only=True) makes every parameter of __init__ keyword-only (module 05). A call must name each value. Use it for configuration objects with many settings, where KNNConfig(15, "manhattan", True) would be unreadable.

@dataclass(slots=True, kw_only=True)
class KNNConfig:
n_neighbors: int = 5
distance: str = "euclidean"
config = KNNConfig(n_neighbors=15)
print(config, KNNConfig.__slots__)
Output
KNNConfig(n_neighbors=15, distance='euclidean') ('n_neighbors', 'distance')
try:
config.n_neighbour = 3 # typo: the field is n_neighbors
except AttributeError as exc:
print(exc)
Output
'KNNConfig' object has no attribute 'n_neighbour' and no __dict__ for setting new attributes

With a plain class or a plain dataclass, the typo would create a new attribute n_neighbour, and the model would still use 5 neighbors. Nothing would warn you.

Two more forms of keyword-only fields exist. field(kw_only=True) marks one field. A pseudo-field annotated with the sentinel dataclasses.KW_ONLY marks all the fields after it. Keyword-only fields also fix a common inheritance error: a subclass cannot add a required field after a parent field with a default, unless the new field is keyword-only.

from dataclasses import KW_ONLY
@dataclass
class 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, after parent fields with defaults: allowed
print(CVRunConfig("knn", n_folds=5))
Output
CVRunConfig(model='knn', seed=42, verbose=False, n_folds=5)

Copy, convert and inspect: replace, asdict, astuple, fields

Section titled “Copy, convert and inspect: replace, asdict, astuple, fields”

The dataclasses module has four functions that work on any data class:

  • replace(obj, **changes) returns a new object with some fields changed. It calls __init__, so __post_init__ runs again and validates the copy. It is the way to “change” a frozen object.
  • asdict(obj) returns a dict of the fields. It works recursively: nested dataclasses, lists and dicts become new dicts and lists, so the result shares no mutable data with the object. Use it to save a config or a report as JSON.
  • astuple(obj) returns the field values as a tuple, also recursively.
  • fields(cls_or_obj) returns one Field object per field, with .name, .type and .default. Use it to write generic code, such as a CSV writer for any dataclass.
import json
from dataclasses import asdict, astuple, fields, replace
base = TrainConfig()
fast = replace(base, learning_rate=0.1, epochs=20)
print(fast)
print(asdict(fast))
print(json.dumps(asdict(fast)))
print(astuple(fast))
print([f.name for f in fields(TrainConfig)])
print(base) # unchanged
Output
TrainConfig(learning_rate=0.1, epochs=20, test_size=0.25, run_name='lr0.1-ep20')
{'learning_rate': 0.1, 'epochs': 20, 'test_size': 0.25, 'run_name': 'lr0.1-ep20'}
{"learning_rate": 0.1, "epochs": 20, "test_size": 0.25, "run_name": "lr0.1-ep20"}
(0.1, 20, 0.25, 'lr0.1-ep20')
['learning_rate', 'epochs', 'test_size', 'run_name']
TrainConfig(learning_rate=0.01, epochs=100, test_size=0.25, run_name='lr0.01-ep100')

replace() recomputed run_name, because __post_init__ ran on the new object. The original base did not change.

replace(base, learning_rate=0) # the copy is validated too
Output
ValueError: learning_rate must be > 0, got 0

Data classes also work with the class patterns of match (module 03). The generated attribute __match_args__ lists the fields in order, so positional patterns work too:

for cfg in [TrainConfig(), TrainConfig(learning_rate=0.5, epochs=5)]:
match cfg:
case TrainConfig(learning_rate=lr) if lr > 0.1:
print(cfg.run_name, "-> high learning rate: watch for divergence")
case TrainConfig(epochs=n):
print(cfg.run_name, f"-> {n} epochs")
print(TrainConfig.__match_args__)
Output
lr0.01-ep100 -> 100 epochs
lr0.5-ep5 -> high learning rate: watch for divergence
('learning_rate', 'epochs', 'test_size')

A magic string is a string literal that has a special meaning in the code, such as "euclidean" in if metric == "euclidean":. Magic strings fail silently. A typo such as "euclidian" is still a valid string: the code falls through to some other branch, and nobody notices.

An enumeration (an enum) is a class with a fixed set of named constants, its members. You create one with a subclass of enum.Enum. Each class attribute becomes a member with a .name and a .value:

from enum import Enum
class Distance(Enum):
EUCLIDEAN = "euclidean"
MANHATTAN = "manhattan"
metric = Distance.EUCLIDEAN
print(metric)
print(repr(metric))
print(metric.name, metric.value)
print(type(metric), isinstance(metric, Distance))
Output
Distance.EUCLIDEAN
<Distance.EUCLIDEAN: 'euclidean'>
EUCLIDEAN euclidean
<enum 'Distance'> True

Member names are UPPER_CASE, like other constants (PEP 8). The members are created once, when the class is created. They are singletons: each member exists as exactly one object, so you may compare members with is.

You can look up a member in three ways:

print(Distance("manhattan")) # by value: parse a config file or a CLI argument
print(Distance["MANHATTAN"]) # by name
print(Distance("euclidean") is Distance.EUCLIDEAN)
for d in Distance: # iteration follows the order of definition
print(d.name, d.value)
print(len(Distance), "manhattan" in Distance, "cosine" in Distance)
Output
Distance.MANHATTAN
Distance.MANHATTAN
True
EUCLIDEAN euclidean
MANHATTAN manhattan
2 True False

The value lookup turns a string from a file into a member and rejects anything else. This is the check that magic strings lack:

Distance("euclidian")
Output
ValueError: 'euclidian' is not a valid Distance

A lookup by a wrong name raises KeyError. The in test with a value ("manhattan" in Distance) works on Python 3.12 and newer.

Enum members behave differently from their values:

print(Distance.EUCLIDEAN == "euclidean") # a plain Enum member is not its value
print(Distance.EUCLIDEAN.value == "euclidean")
print({Distance.EUCLIDEAN: 0.81}[Distance("euclidean")]) # hashable: a dict key
Output
False
True
0.81

Members cannot be reassigned, and plain members have no order: Distance.EUCLIDEAN < Distance.MANHATTAN raises TypeError.

When the values do not matter, let auto() choose them. For Enum, auto() gives the integers 1, 2, 3 and so on:

from enum import auto
class Task(Enum):
REGRESSION = auto()
CLASSIFICATION = auto()
@property
def default_metric(self) -> str:
return "r2" if self is Task.REGRESSION else "accuracy"
print(list(Task))
print(Task.CLASSIFICATION.default_metric)
Output
[<Task.REGRESSION: 1>, <Task.CLASSIFICATION: 2>]
accuracy

An enum is a class, so it can have methods and properties. self is the member. Here each task knows its default metric.

Two values that are equal make the second name an alias of the first member, not a new member. The decorator @enum.unique turns an accidental alias into a ValueError when the class is created.

StrEnum and IntEnum: members that are also strings or ints

Section titled “StrEnum and IntEnum: members that are also strings or ints”

enum.StrEnum (Python 3.11+) makes members that are real strings. enum.IntEnum makes members that are real integers. They compare equal to their values and work wherever a str or an int is expected: in JSON, in f-strings, in pandas columns and in comparisons.

from enum import IntEnum, StrEnum
class Plan(StrEnum):
BASIC = auto() # StrEnum: auto() gives the lowercase name
STANDARD = auto()
PREMIUM = auto()
print(list(Plan))
print(Plan.PREMIUM == "premium", f"plan={Plan.PREMIUM}", Plan("basic").upper())
print(json.dumps({"plan": Plan.PREMIUM}))
class Condition(IntEnum): # houses.csv: condition 1 (worst) to 5 (best)
POOR = 1
FAIR = 2
AVERAGE = 3
GOOD = 4
EXCELLENT = 5
print(Condition(4), repr(Condition(4)), Condition.GOOD > Condition.FAIR)
print(Condition.GOOD == 4, sorted([Condition.EXCELLENT, Condition.POOR]))
Output
[<Plan.BASIC: 'basic'>, <Plan.STANDARD: 'standard'>, <Plan.PREMIUM: 'premium'>]
True plan=premium BASIC
{"plan": "premium"}
4 <Condition.GOOD: 4> True
True [<Condition.POOR: 1>, <Condition.EXCELLENT: 5>]

print(Condition(4)) shows 4, not Condition.GOOD, because an IntEnum member prints like its int. repr() still shows the name.

Enum StrEnum IntEnum
Member is a str / int no yes (str) yes (int)
member == value False True True
<, > between members TypeError compares as strings compares as ints
json.dumps(member) TypeError works works
auto() gives 1, 2, 3… the lowercase member name 1, 2, 3…
Best for options in code: distance, task, strategy text codes in files and APIs ordered levels, numeric codes

The standard library uses these types too. http.HTTPStatus is an IntEnum: HTTPStatus.NOT_FOUND == 404 is True and HTTPStatus.NOT_FOUND.phrase is 'Not Found'. Web frameworks such as Django offer TextChoices, a StrEnum-like type for database fields with fixed values.

match compares the subject with a value pattern when the pattern is a dotted name such as Distance.EUCLIDEAN (module 03). Value patterns compare with ==. So match reads like a table of the choices:

import math
def distance(a: list[float], b: list[float], metric: Distance) -> float:
match metric:
case Distance.EUCLIDEAN:
return math.dist(a, b)
case Distance.MANHATTAN:
return sum(abs(x - y) for x, y in zip(a, b, strict=True))
case _:
raise ValueError(f"unsupported metric: {metric!r}")
a, b = [3.0, 4.0], [0.0, 0.0] # (tenure_months, logins_last_30d) differences
print(distance(a, b, Distance.EUCLIDEAN), distance(a, b, Distance.MANHATTAN))
Output
5.0 7.0

The dot matters. A bare name in a pattern is a capture pattern: it matches anything and binds the subject to that name. Python rejects a capture pattern before other cases:

EUCLIDEAN = Distance.EUCLIDEAN
match Distance.MANHATTAN:
case EUCLIDEAN: # a capture pattern, not the member
print("euclidean")
case _:
print("other")
Output
SyntaxError: name capture 'EUCLIDEAN' makes remaining patterns unreachable

As the last case, a bare name raises no error: it silently matches every member. Always write the enum class name in front of the member. The final case _: catches a member that you add later and forget to handle. With a type checker, typing.assert_never(metric) in that branch reports the missing case before the code runs.

A named tuple is a tuple whose positions also have names. You met collections.namedtuple in module 09 and typing.NamedTuple in module 10. The class form with typing.NamedTuple adds type hints and defaults:

from collections import namedtuple
from typing import NamedTuple
class Neighbor(NamedTuple):
index: int # row number in the training data
distance: float
label: int # churned: 0 or 1
n = Neighbor(index=17, distance=2.236, label=1)
print(n, n.distance, n[1])
index, dist, label = n # unpacks like any tuple
print(index, dist, label, len(n))
print(n._asdict())
print(n._replace(label=0), Neighbor._fields)
NeighborNT = namedtuple("NeighborNT", ["index", "distance", "label"])
print(NeighborNT(17, 2.236, 1))
Output
Neighbor(index=17, distance=2.236, label=1) 2.236 2.236
17 2.236 1 3
{'index': 17, 'distance': 2.236, 'label': 1}
Neighbor(index=17, distance=2.236, label=0) ('index', 'distance', 'label')
NeighborNT(index=17, distance=2.236, label=1)

A named tuple is a tuple. That is its strength and its weakness:

  • It unpacks, indexes, iterates and sorts like a tuple. Functions that return several values can return a named tuple without breaking callers that unpack it. os.stat(), time.localtime() and sys.version_info work this way.
  • It is immutable and hashable (when its items are hashable), and as small as a tuple.
  • It compares equal to any tuple with the same items: Neighbor(17, 2.236, 1) == (17, 2.236, 1) is True, even though the tuple has no names.
  • It sorts by its first field first. Neighbor sorts by index, not by distance. Pass key= to sort by another field (Example 6).
  • It has no validation hook. typing.NamedTuple refuses to let you override __init__ or __new__ (AttributeError: Cannot overwrite NamedTuple attribute __init__), so no check can run when a record is created.
collections.namedtuple typing.NamedTuple @dataclass(frozen=True)
Syntax function call class with annotations class with annotations
Type hints no yes yes
Defaults defaults=[...] label: int = 0 label: int = 0
Is a tuple (index, unpack) yes yes no
== with a plain tuple True True False
Validation hook no no __post_init__
Mutable option no no yes (without frozen)

By default, each instance stores its attributes in a dict, obj.__dict__. A dict can grow, so you can add any attribute at any time. That flexibility costs memory, and it lets typos create new attributes.

A class can declare __slots__: a tuple of the only attribute names its instances may have. Python then reserves a fixed place, a slot, for each name inside the object and creates no __dict__:

import sys
class ReadingPlain:
def __init__(self, sensor_id: str, temperature_c: float) -> None:
self.sensor_id = sensor_id
self.temperature_c = temperature_c
class ReadingSlots:
__slots__ = ("sensor_id", "temperature_c")
def __init__(self, sensor_id: str, temperature_c: float) -> None:
self.sensor_id = sensor_id
self.temperature_c = temperature_c
plain, slotted = ReadingPlain("S1", 20.21), ReadingSlots("S1", 20.21)
print(hasattr(plain, "__dict__"), hasattr(slotted, "__dict__"))
plain.temprature_c = 99.0 # typo: silently adds a new attribute
print(sorted(vars(plain)))
print(sys.getsizeof(slotted))
Output
True False
['sensor_id', 'temperature_c', 'temprature_c']
48
try:
slotted.temprature_c = 99.0
except AttributeError as exc:
print(exc)
Output
'ReadingSlots' object has no attribute 'temprature_c' and no __dict__ for setting new attributes

sys.getsizeof(obj) returns the size in bytes of the object itself. It is shallow: it does not count the objects that the attributes point to, and for a plain instance it does not count the attribute storage. So sys.getsizeof tells you little about a plain class. To measure the real cost of many objects, use tracemalloc (module 10): it counts every byte that Python allocates between start() and get_traced_memory(). Example 7 does this for 8,064 sensor readings.

Rules for __slots__:

  • A class attribute with the same name as a slot is an error (ValueError: 'x' in __slots__ conflicts with class variable). Set defaults in __init__, or use @dataclass(slots=True), which handles defaults for you.
  • An unset slot raises AttributeError when you read it.
  • A subclass without its own __slots__ gets a __dict__ again. Each class in the chain must declare __slots__ (only its new names) to keep the saving.
  • No __dict__ means no vars(obj). Tools that rely on vars(), such as the check_is_fitted of minilearn, need another way to list attributes.
  • Since Python 3.11, CPython stores the attributes of a plain instance compactly and builds the full __dict__ only when code asks for it. So the saving is smaller than older articles claim. Measure it on your Python version.

Use __slots__ for classes with many instances and a fixed shape: rows, readings, graph nodes, tokens. Skip it for estimators and other objects that you create a few times, where flexibility matters more.

More tools: InitVar, _missing_, __members__ and Flag

Section titled “More tools: InitVar, _missing_, __members__ and Flag”

Four smaller tools appear in real code and in the cheat sheet:

  • dataclasses.InitVar[T] marks an __init__ argument that is passed to __post_init__ but is not stored as a field. Use it for a value that you need only to compute other fields, such as a random seed.
  • An enum class method _missing_(cls, value) runs when a lookup by value fails. Return a member to accept the value, or None to raise the usual ValueError. Use it for tolerant parsing, for example of " Premium ".
  • Cls.__members__ maps every name to its member, aliases included. Iteration skips aliases.
  • enum.Flag makes members that combine with | into a set of options, and in tests one option. re.IGNORECASE | re.MULTILINE works this way.
import random
from dataclasses import InitVar
from enum import Flag
@dataclass
class Sampler:
seed: InitVar[int] # passed to __post_init__, not stored
first_draw: int = field(init=False)
def __post_init__(self, seed: int) -> None:
self.first_draw = random.Random(seed).randint(0, 99)
class Tier(StrEnum):
BASIC = auto()
PREMIUM = auto()
@classmethod
def _missing_(cls, value: object) -> "Tier | None":
if isinstance(value, str): # runs only when Tier(value) finds no member
return next((m for m in cls if m.value == value.strip().lower()), None)
return None
class Check(Flag): # data-quality checks to run on a file
NULLS = auto()
RANGE = auto()
DUPLICATES = auto()
enabled = Check.NULLS | Check.RANGE
print(Sampler(42), [f.name for f in fields(Sampler)])
print(Tier(" Premium "), list(Tier.__members__))
print(enabled, Check.RANGE in enabled, Check.DUPLICATES in enabled)
Output
Sampler(first_draw=81) ['first_draw']
premium ['BASIC', 'PREMIUM']
Check.NULLS|RANGE True False

seed is not a field, so it is not in the repr and not in fields(). The tolerant lookup accepts spaces and capitals, and any other text still raises ValueError.

Tool Mutable Checks at run time Memory per record Best for Avoid when
dict yes none high one-off JSON, quick scripts, data with unknown keys the keys are fixed and many functions use them
TypedDict (module 12) yes none (only a type checker) high (it is a dict) typing JSON records you load and pass on unchanged you need methods, defaults or validation
NamedTuple no none low small immutable records, functions that return several values the record must not equal a plain tuple, or needs validation
@dataclass yes __post_init__ medium; low with slots=True configs, reports, results, domain records — (the default choice for a record class)
@dataclass(frozen=True) no __post_init__ medium; low with slots=True value objects, dict keys, splits, versions you update the record often
plain class yes properties, __init__ medium objects with behavior and changing state: estimators, pipelines it only holds data (write a dataclass)
pydantic model (module 44) yes type checks and conversion of every field high untrusted input: API requests, config files from users trusted internal data in a hot loop
flowchart TD
    Q1{"Does it mainly<br/>hold data?"} -- "no: behavior and state" --> PC["plain class"]
    Q1 -- yes --> Q2{"Untrusted input<br/>to validate and convert?"}
    Q2 -- yes --> PY["pydantic model<br/>(module 44)"]
    Q2 -- no --> Q3{"Only a type for<br/>existing dicts?"}
    Q3 -- yes --> TD["TypedDict"]
    Q3 -- no --> Q4{"Must unpack<br/>like a tuple?"}
    Q4 -- yes --> NT["NamedTuple"]
    Q4 -- no --> DC["@dataclass<br/>+ frozen / slots as needed"]

Example 1 — Load a model configuration into a validated dataclass

Section titled “Example 1 — Load a model configuration into a validated dataclass”

Goal: data/config.json has a model section with the model type, the target, test_size, random_state and model parameters. Load it into a dataclass that rejects bad values and unknown keys, make variants for an experiment and save them back as JSON.

with open("data/config.json", encoding="utf-8") as f:
raw = json.load(f)["model"]
print(type(raw).__name__, list(raw))
print(raw["params"])
Output
dict ['type', 'target', 'test_size', 'random_state', 'params']
{'C': 1.0, 'max_iter': 1000}

json.load() returns plain dicts, and nothing checks them. A misspelled key in the file is silently ignored, and a missing key fails only where some code reads it, maybe deep inside a training run.

from pprint import pprint
@dataclass(frozen=True)
class ModelConfig:
type: str
target: str
test_size: float = 0.25
random_state: int = 42
params: dict[str, float] = field(default_factory=dict)
KNOWN_TYPES: ClassVar[tuple[str, ...]] = ("logistic_regression", "knn")
def __post_init__(self) -> None:
if self.type not in self.KNOWN_TYPES:
raise ValueError(f"unknown model type {self.type!r}")
if not 0 < self.test_size < 1:
raise ValueError(f"test_size must be in (0, 1), got {self.test_size}")
config = ModelConfig(**raw)
pprint(config)
Output
ModelConfig(type='logistic_regression',
target='churned',
test_size=0.25,
random_state=42,
params={'C': 1.0, 'max_iter': 1000})

pprint() prints a long dataclass repr with one field per line. ModelConfig(**raw) unpacks the dict into keyword arguments (module 05). Each key must be a field name, so the dataclass checks the keys for free. params is a dict, so it needs default_factory. KNOWN_TYPES is a ClassVar, so it is a shared constant and not a field.

bad_inputs = [
{**raw, "test_size": 25},
{**raw, "type": "random_forest"},
{**raw, "seed": 7}, # the field is called random_state
{"type": "knn"},
]
for bad in bad_inputs:
try:
ModelConfig(**bad)
except (TypeError, ValueError) as exc:
print(f"{type(exc).__name__}: {exc}")
Output
ValueError: test_size must be in (0, 1), got 25
ValueError: unknown model type 'random_forest'
TypeError: ModelConfig.__init__() got an unexpected keyword argument 'seed'
TypeError: ModelConfig.__init__() missing 1 required positional argument: 'target'

__post_init__ rejects the bad values with a ValueError. The generated __init__ rejects the unknown key and the missing target with a TypeError, as any Python function does. Each message names the problem.

variants = [
replace(config, test_size=t, random_state=s) for t in (0.2, 0.3) for s in (0, 1)
]
for v in variants:
print(v.test_size, v.random_state, v.params)
print(config.test_size, variants[0].params is config.params)
Output
0.2 0 {'C': 1.0, 'max_iter': 1000}
0.2 1 {'C': 1.0, 'max_iter': 1000}
0.3 0 {'C': 1.0, 'max_iter': 1000}
0.3 1 {'C': 1.0, 'max_iter': 1000}
0.25 True

Each variant is a new frozen object, and config is unchanged. replace() copies the field values, not the objects inside them: all variants share one params dict. With a frozen class, nobody can assign a new params, but config.params["C"] = 10 would still change every variant. Treat the dict as read-only, or store a tuple of pairs.

Step 5 — Save the experiment plan as JSON

Section titled “Step 5 — Save the experiment plan as JSON”
plan = json.dumps([asdict(v) for v in variants[:2]], indent=1)
print(plan)
reloaded = [ModelConfig(**d) for d in json.loads(plan)]
print(reloaded == variants[:2])
Output
[
{
"type": "logistic_regression",
"target": "churned",
"test_size": 0.2,
"random_state": 0,
"params": {
"C": 1.0,
"max_iter": 1000
}
},
{
"type": "logistic_regression",
"target": "churned",
"test_size": 0.2,
"random_state": 1,
"params": {
"C": 1.0,
"max_iter": 1000
}
}
]
True

asdict() gives plain dicts that json.dumps() can write. ModelConfig(**d) rebuilds equal objects, and the validation runs again on the way in. This round trip is how many tools store experiment configs.

Common mistakes:

  • params: dict = {}. The class fails with ValueError: mutable default <class 'dict'> for field params is not allowed. Use field(default_factory=dict).
  • Accepting **kwargs in a config class “to be flexible”. Unknown keys then pass silently, which hides typos. Let the generated __init__ reject them.
  • Validating in a separate function that callers may forget. Put the checks in __post_init__, so no invalid object can exist.

Goal: Split the 5,000 customers of data/customers.csv into training and test rows once, and make sure no later code can move a row from one set to the other. Then reuse the split as a cache key for model scores.

Step 1 — Write a frozen Split with checks

Section titled “Step 1 — Write a frozen Split with checks”
import csv
import random
with open("data/customers.csv", encoding="utf-8", newline="") as f:
customers = list(csv.DictReader(f))
churned = [int(row["churned"]) for row in customers]
@dataclass(frozen=True)
class Split:
train: tuple[int, ...] # row indices
test: tuple[int, ...]
n_samples: int = field(init=False)
def __post_init__(self) -> None:
if set(self.train) & set(self.test):
raise ValueError("a row is in both train and test")
object.__setattr__(self, "n_samples", len(self.train) + len(self.test))
def holdout(n_samples: int, test_size: float, seed: int) -> Split:
order = list(range(n_samples))
random.Random(seed).shuffle(order)
n_test = round(n_samples * test_size)
test, train = sorted(order[:n_test]), sorted(order[n_test:])
return Split(train=tuple(train), test=tuple(test))
split = holdout(len(customers), test_size=0.25, seed=42)
print(len(split.train), len(split.test), split.n_samples, split.test[:5])
Output
3750 1250 5000 (0, 7, 8, 10, 15)

random.Random(42) is a generator with its own seed, so the split is the same on every run. __post_init__ checks that the two sets do not overlap and computes n_samples. The class is frozen, so it sets the derived field with object.__setattr__.

Step 2 — Check that the split is representative

Section titled “Step 2 — Check that the split is representative”
def churn_rate(indices: tuple[int, ...]) -> float:
return sum(churned[i] for i in indices) / len(indices)
print(f"train {churn_rate(split.train):.3f} test {churn_rate(split.test):.3f}")
Output
train 0.191 test 0.196

Both sets have a churn rate close to the 19.26% of the whole file, so the random split did not create a biased test set. Module 37 makes sure of this with a stratified split; the project of this module writes one.

split.test = split.test + (0,) # "just add one row to the test set"
Output
dataclasses.FrozenInstanceError: cannot assign to field 'test'

Moving a training row into the test set after you have seen the scores is a form of data leakage: the test score no longer measures performance on unseen data. A frozen split makes this edit impossible by accident.

score_cache: dict[tuple[Split, str], float] = {}
score_cache[(split, "knn-k15")] = 0.781 # a score computed earlier
same_split = holdout(len(customers), test_size=0.25, seed=42)
other_split = holdout(len(customers), test_size=0.25, seed=7)
print(same_split == split, same_split is split)
print((same_split, "knn-k15") in score_cache, (other_split, "knn-k15") in score_cache)
Output
True False
True False

The frozen dataclass hashes by its fields. A split rebuilt with the same seed is a different object, but it is equal and has the same hash, so the cache finds the stored score. A split with another seed misses.

@dataclass(frozen=True)
class ListSplit:
train: list[int]
test: list[int]
leaky = ListSplit(train=[0, 1, 2], test=[3])
leaky.test.append(0) # frozen does not stop this
print(leaky)
print(hash(leaky))
Output
ListSplit(train=[0, 1, 2], test=[3, 0])
TypeError: unhashable type: 'list'

Frozen only blocks assignment to the fields. The list inside can still change, so row 0 is now in both sets. hash() fails as well, and it would fail even without the append, because a list is unhashable. Tuples make the whole object immutable.

Common mistakes:

  • Using a non-frozen dataclass as a dict key. It raises TypeError: unhashable type. Add frozen=True.
  • Storing lists in a frozen dataclass and believing it is immutable. Use tuples, frozenset or another frozen dataclass.
  • Writing self.n_samples = ... in __post_init__ of a frozen class. It raises FrozenInstanceError. Use object.__setattr__(self, "n_samples", ...).

Goal: Score three price models on data/houses.csv and rank them on two metrics: R² (higher is better) and RMSE (lower is better). Replace the 40-line ModelScore class of module 20 with a dataclass.

Step 1 — Fit three models on a time-based split

Section titled “Step 1 — Fit three models on a time-based split”
import statistics
with open("data/houses.csv", encoding="utf-8", newline="") as f:
houses = [(float(r["sqft"]), float(r["price"])) for r in csv.DictReader(f)]
train_h, test_h = houses[:2250], houses[2250:] # sorted by sold_date: train on the past
x_train = [s for s, _ in train_h]
y_train = [p for _, p in train_h]
y_test = [p for _, p in test_h]
line = statistics.linear_regression(x_train, y_train)
predictions = {
"mean baseline": [statistics.fmean(y_train)] * len(test_h),
"median baseline": [statistics.median(y_train)] * len(test_h),
"linear (sqft)": [line.intercept + line.slope * s for s, _ in test_h],
}
print(f"slope {line.slope:.1f} USD per sqft, intercept {line.intercept:,.0f} USD")
Output
slope 318.5 USD per sqft, intercept -124,046 USD

statistics.linear_regression() fits the least-squares line of module 18’s LinearRegression in one call. The two baselines predict one constant for every house.

@dataclass(frozen=True, order=True)
class ModelScore:
rank_key: tuple[float, str] = field(init=False, repr=False)
model: str = field(compare=False)
metric: str = field(compare=False)
value: float = field(compare=False)
greater_is_better: bool = field(default=True, compare=False, repr=False)
def __post_init__(self) -> None:
signed = self.value if self.greater_is_better else -self.value
object.__setattr__(self, "rank_key", (signed, self.model))
def __str__(self) -> str:
return f"{self.model:<16} {self.metric:>4} = {self.value:,.3f}"

The order methods compare only fields with compare=True. Here that is the single field rank_key, so “less than” means “worse than” for both kinds of metric. The model name inside rank_key breaks ties. rank_key is the first field, but it has init=False, so it is not a parameter and does not break the rule about defaults.

def r2(y_true: list[float], y_pred: list[float]) -> float:
mean = statistics.fmean(y_true)
ss_res = sum((t - p) ** 2 for t, p in zip(y_true, y_pred, strict=True))
return 1 - ss_res / sum((t - mean) ** 2 for t in y_true)
def rmse(y_true: list[float], y_pred: list[float]) -> float:
pairs = zip(y_true, y_pred, strict=True)
return math.sqrt(statistics.fmean((t - p) ** 2 for t, p in pairs))
r2_board = [ModelScore(m, "r2", r2(y_test, p)) for m, p in predictions.items()]
rmse_board = [
ModelScore(m, "rmse", rmse(y_test, p), greater_is_better=False)
for m, p in predictions.items()
]
for board in (r2_board, rmse_board):
for score in sorted(board, reverse=True):
print(score)
print("best:", max(board).model)
Output
linear (sqft) r2 = 0.550
mean baseline r2 = -0.010
median baseline r2 = -0.158
best: linear (sqft)
linear (sqft) rmse = 223,691.326
mean baseline rmse = 335,078.658
median baseline rmse = 358,737.424
best: linear (sqft)

The same sorted(..., reverse=True) and max() work for both metrics. The linear model wins on both. Both baselines have a negative R²: the test houses were sold later and cost more than the training mean.

Step 4 — Read the generated repr and equality

Section titled “Step 4 — Read the generated repr and equality”
print(r2_board[2])
print(repr(r2_board[2]))
same = ModelScore("linear (sqft)", "r2", r2_board[2].value)
print(same == r2_board[2], len({same, r2_board[2]}))
Output
linear (sqft) r2 = 0.550
ModelScore(model='linear (sqft)', metric='r2', value=0.5499276311256265)
True 1

print() uses the __str__ you wrote. The generated __repr__ hides rank_key and greater_is_better, because they have repr=False. Two scores with the same key are equal, so a set keeps one of them.

Common mistakes:

  • Putting the fields in the wrong order. With order=True, the first compared field decides first. A model: str field first would sort alphabetically by name.
  • Expecting compare=False to affect only sorting. It also removes the field from == and from the hash.
  • Comparing an R² score with an RMSE score. The dataclass does not stop it. Module 20’s version raised an error; add a check in a custom __lt__ if you mix metrics in one list.

Example 4 — Choose the distance metric with an Enum

Section titled “Example 4 — Choose the distance metric with an Enum”

Goal: A KNN churn model compares customers by tenure_months and logins_last_30d. Its distance metric comes from a settings file as text. Parse it into an enum, reject typos, and see how the metric changes the nearest neighbors of one customer.

class Distance(Enum):
EUCLIDEAN = "euclidean"
MANHATTAN = "manhattan"
CHEBYSHEV = "chebyshev"
def between(self, a: list[float], b: list[float]) -> float:
diffs = [abs(x - y) for x, y in zip(a, b, strict=True)]
match self:
case Distance.EUCLIDEAN:
return math.sqrt(sum(d * d for d in diffs))
case Distance.MANHATTAN:
return sum(diffs)
case Distance.CHEBYSHEV:
return max(diffs)
raise AssertionError(f"unhandled metric {self!r}")
for d in Distance:
print(f"{d.name:<9} {d.between([3.0, 4.0], [0.0, 0.0])}")
Output
EUCLIDEAN 5.0
MANHATTAN 7.0
CHEBYSHEV 4.0

The Chebyshev distance is the largest difference over all features. Each member carries its own formula through the method. The match on self lists the three formulas side by side, and the final raise catches a member that someone adds without a formula.

Step 2 — Parse the setting and reject typos

Section titled “Step 2 — Parse the setting and reject typos”
def parse_distance(text: str) -> Distance:
try:
return Distance(text.strip().lower())
except ValueError:
valid = ", ".join(d.value for d in Distance)
raise ValueError(f"unknown distance {text!r}; choose one of: {valid}") from None
for text in ["euclidean", " Manhattan ", "euclidian"]:
try:
print(repr(parse_distance(text)))
except ValueError as exc:
print(exc)
Output
<Distance.EUCLIDEAN: 'euclidean'>
<Distance.MANHATTAN: 'manhattan'>
unknown distance 'euclidian'; choose one of: euclidean, manhattan, chebyshev

The lookup by value accepts only the three values. Iterating over the enum builds the list of valid choices for the error message, so it stays correct when a member is added. from None hides the first, less helpful ValueError.

Step 3 — Find the nearest customers under each metric

Section titled “Step 3 — Find the nearest customers under each metric”
features = [[float(r["tenure_months"]), float(r["logins_last_30d"])] for r in customers]
query = [6.0, 2.0] # a new customer: 6 months, 2 logins in 30 days
for metric in Distance:
def key(i: int, metric: Distance = metric) -> tuple[float, int]:
return metric.between(query, features[i]), i # ties: lower row number
top = sorted(range(len(features)), key=key)[:5]
rate = sum(churned[i] for i in top) / len(top)
print(f"{metric.value:<9} rows {top} churn among 5 nearest: {rate:.0%}")
Output
euclidean rows [3990, 4006, 3745, 3793, 3834] churn among 5 nearest: 60%
manhattan rows [3990, 4006, 3745, 3793, 3834] churn among 5 nearest: 60%
chebyshev rows [3990, 4006, 3736, 3738, 3745] churn among 5 nearest: 80%

The key (distance, i) breaks ties by row number, so the result is the same on every run. The metric changes which customers count as nearest. That is why it is a hyperparameter, and why the code should name it with an enum, not a free string.

Common mistakes:

  • Comparing a plain Enum member with its string: metric == "euclidean" is always False. Compare members (metric is Distance.EUCLIDEAN) or parse the string first.
  • Writing case EUCLIDEAN: without the class name. It is a capture pattern that matches everything.
  • Building the list of valid values by hand in the error message. It goes out of date. Iterate over the enum.

Example 5 — Parse categorical columns with StrEnum and IntEnum

Section titled “Example 5 — Parse categorical columns with StrEnum and IntEnum”

Goal: Turn the text column contract of data/customers.csv and the number column condition of data/houses.csv into enum members. Report churn by contract in a fixed order, compare house prices by condition, and catch bad codes in raw data.

class Contract(StrEnum):
MONTH_TO_MONTH = "month-to-month"
ONE_YEAR = "one-year"
TWO_YEAR = "two-year"
contracts = [Contract(row["contract"]) for row in customers]
print(contracts[:2], contracts[0] == "two-year")
Output
[<Contract.TWO_YEAR: 'two-year'>, <Contract.TWO_YEAR: 'two-year'>] True

The values contain dashes, so auto() would not produce them. Write them out. Each member is still a real string, so it compares equal to the text in the file and would write back to a CSV unchanged.

from collections import Counter
total = Counter(contracts)
lost = Counter(c for c, y in zip(contracts, churned, strict=True) if y == 1)
for contract in Contract: # definition order: shortest commitment first
rate = lost[contract] / total[contract]
print(f"{contract:<15} {total[contract]:>5,} customers churn {rate:.1%}")
Output
month-to-month 2,784 customers churn 29.6%
one-year 1,225 customers churn 8.8%
two-year 991 customers churn 3.2%

Iterating over the enum gives the rows in a meaningful order, not alphabetical and not by size. f"{contract:<15}" works because a StrEnum member formats like its string value. Month-to-month customers churn nine times more often than two-year customers.

Step 3 — Compare prices by an ordered IntEnum

Section titled “Step 3 — Compare prices by an ordered IntEnum”
with open("data/houses.csv", encoding="utf-8", newline="") as f:
house_rows = list(csv.DictReader(f))
by_condition: dict[Condition, list[float]] = {c: [] for c in Condition}
for row in house_rows:
by_condition[Condition(int(row["condition"]))].append(float(row["price"]))
for c in Condition:
prices = by_condition[c]
print(f"{c.name:<9} {len(prices):>5,} median {statistics.median(prices):>9,.0f}")
good = [p for c, ps in by_condition.items() if c >= Condition.GOOD for p in ps]
print(f"GOOD or better: {len(good):,} houses")
Output
POOR 183 median 295,000
FAIR 600 median 325,250
AVERAGE 1,413 median 381,500
GOOD 607 median 425,000
EXCELLENT 197 median 486,500
GOOD or better: 804 houses

Condition(int(...)) turns the number from the file into a named level. c >= Condition.GOOD works because IntEnum members are ordered ints. A plain Enum would need a custom __lt__ for this.

raw_codes = ["one-year", "Month-to-month", "two year", "month-to-month", ""]
valid, problems = [], []
for line, code in enumerate(raw_codes, start=2): # line 1 is the header
try:
valid.append(Contract(code))
except ValueError as exc:
problems.append(f"line {line}: {exc}")
print(valid)
print("\n".join(problems))
Output
[<Contract.ONE_YEAR: 'one-year'>, <Contract.MONTH_TO_MONTH: 'month-to-month'>]
line 3: 'Month-to-month' is not a valid Contract
line 4: 'two year' is not a valid Contract
line 6: '' is not a valid Contract

The enum is the single source of truth for valid codes. Typed-in variants such as "two year" or a different case fail loudly, with the line number. Module 26 cleans such values before this check.

Common mistakes:

  • Using auto() in a StrEnum for values that are not the lowercase name, such as "month-to-month". auto() would give "month_to_month", and every lookup from the file would fail.
  • Expecting print(Condition.GOOD) to show the name. An IntEnum member prints as its number. Use .name.
  • Sorting a report by the category string. Iterate over the enum to get the order you defined.

Example 6 — Return neighbors as NamedTuples

Section titled “Example 6 — Return neighbors as NamedTuples”

Goal: A KNN classifier must explain each prediction: which training rows were the neighbors, how far away they were and what their labels were. Return each neighbor as a Neighbor(index, distance, label) named tuple.

train_rows = list(split.train)
def neighbors_of(query: list[float], k: int, metric: Distance) -> list[Neighbor]:
candidates = [
Neighbor(i, metric.between(query, features[i]), churned[i]) for i in train_rows
]
return sorted(candidates, key=lambda n: (n.distance, n.index))[:k]
found = neighbors_of([6.0, 2.0], k=5, metric=Distance.EUCLIDEAN)
for n in found:
print(n)
Output
Neighbor(index=3745, distance=1.0, label=0)
Neighbor(index=3793, distance=1.0, label=1)
Neighbor(index=3834, distance=1.0, label=0)
Neighbor(index=3855, distance=1.0, label=0)
Neighbor(index=3928, distance=1.0, label=0)

Each neighbor is one small immutable record. The key (n.distance, n.index) sorts by distance and breaks ties by row number. Without a key, sorted() would sort by index, the first field.

votes = Counter(label for _, _, label in found)
prediction = votes.most_common(1)[0][0]
mean_distance = statistics.fmean(n.distance for n in found)
print(votes, "->", prediction, f"(mean distance {mean_distance:.2f})")
Output
Counter({0: 4, 1: 1}) -> 0 (mean distance 1.00)

A named tuple unpacks like a plain tuple, so for _, _, label in found works. The names make the other lines readable: n.distance instead of n[1].

explanation = {
"query": [6.0, 2.0],
"prediction": prediction,
"neighbors": [n._asdict() for n in found[:1]],
}
print(json.dumps(explanation))
print(json.dumps(found[0]))
Output
{"query": [6.0, 2.0], "prediction": 0, "neighbors": [{"index": 3745, "distance": 1.0, "label": 0}]}
[3745, 1.0, 0]

_asdict() gives a dict with the field names. Without it, json.dumps() writes a named tuple as a plain JSON list and loses the names. The leading underscore of _asdict does not mean “private” here: the named tuple API uses it so that the method names cannot clash with your field names.

Point = namedtuple("Point", ["x", "y", "z"])
first = found[0]
print(first == tuple(first), first == Point(*first))
print(first == Neighbor(first.index, first.distance, first.label))
Output
True True
True

A named tuple compares as a tuple. It equals a plain tuple and an unrelated named tuple with the same items. A frozen dataclass compares equal only to an instance of the same class. Choose the dataclass when that difference matters.

Common mistakes:

  • Sorting named tuples without key=. The first field decides, and for Neighbor that is the row index, not the distance.
  • Trying n.label = 0. Named tuples are immutable (AttributeError: can't set attribute). Use n._replace(label=0) to get a changed copy.
  • Writing a named tuple to JSON without _asdict(). The names are lost.

Example 7 — Measure the memory of 8,064 sensor readings

Section titled “Example 7 — Measure the memory of 8,064 sensor readings”

Goal: A monitoring job keeps every reading of data/sensors.csv in memory. Compare five ways to store one reading: a dict, a plain class, a dataclass, a dataclass with slots=True and a NamedTuple.

def to_float(text: str) -> float | None:
return float(text) if text else None # 22 temperatures are blank
with open("data/sensors.csv", encoding="utf-8", newline="") as f:
values = [
(r["timestamp"], r["sensor_id"], to_float(r["temperature_c"]), r["status"])
for r in csv.DictReader(f)
]
print(len(values), values[0])
Output
8064 ('2024-05-01T00:00:00', 'S1', 20.21, 'ok')

The strings and floats exist now. The measurement below then counts only the record objects that hold them, not the values themselves.

class ReadingClass:
def __init__(
self, timestamp: str, sensor_id: str, temperature_c: float | None, status: str
) -> None:
self.timestamp = timestamp
self.sensor_id = sensor_id
self.temperature_c = temperature_c
self.status = status
@dataclass
class ReadingData:
timestamp: str
sensor_id: str
temperature_c: float | None
status: str
@dataclass(slots=True)
class ReadingSlotted:
timestamp: str
sensor_id: str
temperature_c: float | None
status: str
class ReadingTuple(NamedTuple):
timestamp: str
sensor_id: str
temperature_c: float | None
status: str
def as_dict(
timestamp: str, sensor_id: str, temperature_c: float | None, status: str
) -> dict[str, str | float | None]:
return {
"timestamp": timestamp,
"sensor_id": sensor_id,
"temperature_c": temperature_c,
"status": status,
}
first = values[0]
print(sys.getsizeof(ReadingClass(*first)), sys.getsizeof(ReadingSlotted(*first)))
Output
48 64

sys.getsizeof suggests that the plain class is smaller than the slotted one. That is the shallow-size trap: it does not count where the plain instance keeps its attribute values.

import tracemalloc
def bytes_per_record(factory) -> float:
tracemalloc.start()
records = [factory(*v) for v in values]
used, _peak = tracemalloc.get_traced_memory()
tracemalloc.stop()
return used / len(records)
baseline = bytes_per_record(lambda *v: None) # the list of 8,064 references alone
for factory in [as_dict, ReadingClass, ReadingData, ReadingSlotted, ReadingTuple]:
per_record = bytes_per_record(factory) - baseline
total_kib = per_record * len(values) / 1024
name = factory.__name__
print(f"{name:<15} {per_record:>5.0f} bytes/reading {total_kib:>6.0f} KiB")
Output
as_dict 184 bytes/reading 1446 KiB
ReadingClass 104 bytes/reading 822 KiB
ReadingData 104 bytes/reading 822 KiB
ReadingSlotted 64 bytes/reading 504 KiB
ReadingTuple 80 bytes/reading 630 KiB

tracemalloc counts every block that Python allocates while the records are built. Subtracting the baseline removes the cost of the list itself. A dict per record costs the most. A slotted dataclass costs about 40% less than a plain instance, and a NamedTuple sits between them. The values come from Python 3.13. Other versions give other numbers: measure on yours before you decide.

row = ReadingSlotted(*values[0])
try:
row.temprature_c = 30.0
except AttributeError as exc:
print(exc)
row.temperature_c = 30.0 # the real field still changes: slots are not frozen
print(row)
Output
'ReadingSlotted' object has no attribute 'temprature_c' and no __dict__ for setting new attributes
ReadingSlotted(timestamp='2024-05-01T00:00:00', sensor_id='S1', temperature_c=30.0, status='ok')

Slots fix the set of attribute names, not the values. Combine slots=True with frozen=True when the values must not change either.

Common mistakes:

  • Trusting sys.getsizeof for objects that hold other objects. It is shallow. Measure many objects with tracemalloc.
  • Measuring while the values themselves are created. You then compare the cost of strings and floats, which is the same for every record type.
  • Adding __slots__ to every class “for speed”. The saving matters for many thousands of small objects. For a handful of estimators, it only removes flexibility.
Mistake Symptom Fix
scores: list[float] = [] in a dataclass ValueError: mutable default <class 'list'> for field scores is not allowed: use default_factory scores: list[float] = field(default_factory=list)
A field without a default after one with a default TypeError: non-default argument 'model' follows default argument 'learning_rate' Reorder the fields, or make the later ones keyword-only
Expecting the type hints to be checked FitReport("knn", "many", None) is accepted Check in __post_init__, run mypy, or use pydantic for untrusted input
Using a plain dataclass as a dict key TypeError: unhashable type @dataclass(frozen=True)
Assigning in __post_init__ of a frozen class FrozenInstanceError: cannot assign to field object.__setattr__(self, "name", value)
A list field in a frozen dataclass the list still changes; hash() fails Store tuples or frozensets
Wrong field order with order=True records sort by the wrong field Put the sort fields first, or use a rank_key field and compare=False on the others
Zero-argument super() in a method of a slots=True dataclass (3.12, 3.13) TypeError: super(type, obj): obj ... is not an instance or subtype of type Upgrade to 3.14, or write __slots__ by hand
metric == "euclidean" with a plain Enum member always False Compare members, or parse the string with Distance(text)
case EUCLIDEAN: in match SyntaxError: name capture ... makes remaining patterns unreachable, or it matches everything case Distance.EUCLIDEAN:
json.dumps() of a plain Enum member TypeError: Object of type Distance is not JSON serializable Dump .value, or use StrEnum
auto() in a StrEnum for values with dashes or capitals lookups from the file raise ValueError Write the values out
Sorting NamedTuple records without key= sorted by the first field sorted(items, key=lambda n: n.distance)
A named tuple equals a plain tuple Neighbor(1, 0.5, 0) == (1, 0.5, 0) is True Use a frozen dataclass when the type must matter
A class attribute with the same name as a slot ValueError: 'x' in __slots__ conflicts with class variable Set defaults in __init__, or use @dataclass(slots=True)
A subclass of a slotted class without __slots__ instances get a __dict__ again; no saving Declare __slots__ (the new names only) in every subclass
Measuring memory with sys.getsizeof a plain instance looks smaller than a slotted one Measure many objects with tracemalloc
  • Web and APIs: FastAPI and pydantic describe request bodies with classes that look like dataclasses (module 44). http.HTTPStatus is an IntEnum, and Django’s TextChoices gives database fields a fixed set of values.
  • Command-line tools and services: a frozen dataclass holds the settings parsed by argparse or read from a TOML file, so no part of the program can change them later. asdict() writes them to the log at start-up.
  • Automation and state machines: an Enum such as JobState.QUEUED, RUNNING, DONE, FAILED, matched with match, models the states of a build job, an order or a deployment.
  • High-volume objects: parsers, game engines, network libraries and ORMs use __slots__ or slotted dataclasses for millions of small objects such as tokens, packets and rows.
  • @dataclass generates __init__, __repr__ and __eq__ from the annotated fields. Type hints name the fields; they are not checked at run time.
  • Fields without defaults come first. Mutable defaults are rejected: use field(default_factory=list). field() also controls init, repr, compare and kw_only.
  • __post_init__ validates values and computes derived fields. replace() runs it again on the copy.
  • frozen=True blocks assignment and adds a hash, so instances can be dict keys. It is shallow: store tuples, not lists.
  • order=True sorts by the fields as a tuple, in class order. slots=True fixes the attributes and saves memory. kw_only=True forces named arguments.
  • asdict() and astuple() convert recursively; fields() lists the fields for generic code.
  • An Enum names a fixed set of choices. Look members up by value (Distance("manhattan")) or name (Distance["MANHATTAN"]), iterate in definition order, and match them with dotted value patterns.
  • StrEnum and IntEnum members are real strings and ints: good for files, JSON and ordered levels, at the cost of some type safety.
  • A NamedTuple is an immutable tuple with names: it unpacks and sorts like a tuple and equals plain tuples.
  • __slots__ removes the per-instance __dict__. Measure its effect with tracemalloc, not sys.getsizeof.
  • Default to a dataclass for records. Use a plain class for objects with behavior, TypedDict to type existing dicts, NamedTuple for tuple-like results and pydantic for untrusted input.

Q1. Which methods does a plain @dataclass generate, and which does it not generate?

Answer

It generates __init__, __repr__ and __eq__ (and __match_args__). It does not generate the order methods (__lt__ and the others) unless you pass order=True, and it sets __hash__ to None, so instances are unhashable unless you pass frozen=True or unsafe_hash=True.

Q2. Why does @dataclass reject tags: list[str] = [], and what do you write instead?

Answer

The class body runs once, so one list would be shared by every instance: a change in one object would appear in all of them. @dataclass raises ValueError: mutable default <class 'list'> for field tags is not allowed: use default_factory. Write tags: list[str] = field(default_factory=list), which calls list() for each new instance.

Q3. A frozen dataclass Split has a field test: list[int]. Is the split immutable? What happens with hash(split)?

Answer

No. frozen=True blocks assignment to the fields, but split.test.append(0) still changes the list. hash(split) raises TypeError: unhashable type: 'list', because the generated hash hashes the field values. Store the indices as a tuple.

Q4. @dataclass(order=True) defines the fields model: str and score: float, in that order. How does sorted() order the instances?

Answer

By model first, alphabetically, and by score only between records with the same model name. The order methods compare the fields as a tuple in class order. Put score first, or add a sort-key field and mark the others with compare=False.

Q5. When does __post_init__ run? Does it run after config.learning_rate = -1 or after replace(config, learning_rate=-1)?

Answer

It runs at the end of the generated __init__. A plain assignment does not call __init__, so it does not run there. replace() creates a new object through __init__, so it runs, and the copy is validated. Use frozen=True to stop the unchecked assignment.

Q6. What do Distance("manhattan"), Distance["MANHATTAN"] and Distance("cosine") do?

Answer

The first looks up a member by value and returns Distance.MANHATTAN. The second looks it up by name and returns the same member. The third raises ValueError: 'cosine' is not a valid Distance, because no member has that value.

Q7. class Distance(Enum) has EUCLIDEAN = "euclidean". Why is Distance.EUCLIDEAN == "euclidean" False? What changes with StrEnum?

Answer

A plain Enum member is its own object, not a string, and it only equals itself. Its value is Distance.EUCLIDEAN.value. With class Distance(StrEnum), each member is also a str, so it compares equal to "euclidean", formats as euclidean and works in json.dumps().

Q8. What is wrong with case EUCLIDEAN: in a match statement on a Distance member?

Answer

A bare name is a capture pattern. It matches any value and binds it to the name EUCLIDEAN. Before other cases, Python raises SyntaxError: name capture 'EUCLIDEAN' makes remaining patterns unreachable. As the last case, it silently matches every member. Write the dotted value pattern case Distance.EUCLIDEAN:.

Q9. Neighbor(index, distance, label) is a NamedTuple. What does sorted(neighbors) sort by, and what does Neighbor(3, 0.5, 1) == (3, 0.5, 1) give?

Answer

sorted() compares the tuples item by item, so it sorts by index first. Use key=lambda n: n.distance. The comparison gives True: a named tuple equals any tuple with the same items.

Q10. Why does sys.getsizeof() give a misleading answer for a plain object, and what do you use instead?

Answer

sys.getsizeof() is shallow. It counts only the object’s own memory, not its attribute storage and not the objects the attributes point to. A plain instance can look smaller than a slotted one. Create many objects between tracemalloc.start() and tracemalloc.get_traced_memory() and divide by their number.

Q11. You add __slots__ = ("x",) to a class and also write x = 0 in the class body as a default. What happens?

Answer

Python raises ValueError: 'x' in __slots__ conflicts with class variable when it creates the class. The slot and the class attribute would need the same name in the class. Set the default in __init__, or use @dataclass(slots=True) with x: int = 0, which handles it.

Q12. You receive JSON order requests from a public web form. Which tool from this module’s decision table do you use to represent them, and why?

Answer

A pydantic model (module 44). The input is untrusted, so each field needs type checks and conversion, such as "3" to 3, with clear error messages. A dataclass does not check types, and a TypedDict only helps a type checker. Inside the program, after validation, a dataclass is fine.

Your progress

0 / 4 done

  • Exercises: 26 exercises on dataclasses, enums, named tuples and slots, with hints and full solutions.
  • Mini-project: add train_test_split with a frozen Split, a Distance enum for KNNClassifier, confusion_matrix and a classification_report of dataclasses to minilearn.
  • Cheat sheet: every dataclass option, the enum API, named tuples, slots and the decision table on one page.
  • Next module: 22. Design principles and patterns applies SOLID, strategy, factory, template method and observer to minilearn, and shows when a pattern is not worth it.