Advanced OOP, Part 2: Dataclasses, Enums & Protocols
"runing" because of a typo. Nothing fails. The dashboard filter for "running" simply never shows it, and you spend an hour finding out why.Run, from start to finish. @dataclass writes the boring parts of a class that mostly holds data, and we use it to build Run. Enum gives a fixed set of choices real names, and we use it for the status of a Run. Protocol lets you say "anything with a score method" and have a checker verify it, and we use it to rank runs.You have seen classes, inheritance, abstract base classes and type hints already. Next in the track comes Python's data model, and later FastAPI, where request and response shapes are written with exactly these ideas.
After this lesson, you will be able to:
- Write a record class with @dataclass, including defaults, field(default_factory=...) and validation in __post_init__
- Choose between frozen=True, order=True and slots=True and say what each one changes
- Replace magic strings with Enum or StrEnum and explain what fails, and when, on a bad value
- Describe an interface with Protocol and say what a type checker verifies that Python itself does not
- Pick between a dataclass, a plain class, a NamedTuple and a Pydantic model for a given job
Before you start
A note on names. Methods such as__init__,__repr__,__eq__and__post_init__start and end with two underscores. Python calls them for you:__eq__runs for==, and__post_init__runs right after the generated__init__. The full list belongs to the lesson on Python's data model, and nothing here depends on it.
#Why a Plain Class Is Not Enough for Records
Start with the class you would write today, holding one training run.
class Run:
def __init__(self, name, learning_rate):
self.name = name
self.learning_rate = learning_rate
a = Run("baseline", 0.001)
b = Run("baseline", 0.001)
print(a)
print(a == b)Output:
<__main__.Run object at 0x104a3c2d0>
False
__eq__ method Python compares identity: are these the same object?__repr__ and __eq__ by hand, listing every field in each. Add an epochs field next month and you edit three places. Forget one and nothing complains.#Dataclass Basics: Fields, Defaults and Validation
@dataclass decorator (a function that takes your class and returns it with more methods added) generates __init__, __repr__ and __eq__ from that list.from dataclasses import dataclass
@dataclass
class Run:
name: str
learning_rate: float
epochs: int = 10
a = Run("baseline", 0.001)
b = Run("baseline", 0.001)
print(a)
print(a == b)Output:
Run(name='baseline', learning_rate=0.001, epochs=10)
True
a.text works, methods work, isinstance works. The decorator only saved you the typing, and it keeps the three generated methods in step with the field list.#Defaults and the mutable-default trap
epochs: int = 10) can be left out when you create the object. Two rules come with that. A field without a default may not come after one with a default, and a default may not be a list, dict or set.This class tries to give every Run an empty list of metrics. What happens when Python runs the class definition?
from dataclasses import dataclass, field
try:
@dataclass
class Bad:
metrics: list[float] = []
except ValueError as e:
print("ValueError:", e)
@dataclass
class Run:
name: str
learning_rate: float
metrics: list[float] = field(default_factory=list)
a = Run("baseline", 0.001)
b = Run("wide", 0.01)
a.metrics.append(0.52)
print(a.metrics, b.metrics)Output:
ValueError: mutable default <class 'list'> for field metrics is not allowed: use default_factory
[0.52] []
default_factory takes any function that needs no arguments: list, dict, set, or your own. Python calls it once per new object, so each Run gets a fresh list.#Validation and derived values in __post_init__
__init__ only stores what you pass. To reject bad input or tidy a field, define __post_init__. Python calls it automatically at the end of __init__.from dataclasses import dataclass, field
@dataclass
class Run:
name: str
learning_rate: float = 0.001
epochs: int = 10
metrics: list[float] = field(default_factory=list)
def __post_init__(self) -> None:
if self.learning_rate <= 0:
raise ValueError(f"learning_rate must be positive, got {self.learning_rate}")
self.name = self.name.strip()
@property
def best_loss(self) -> float | None:
return min(self.metrics) if self.metrics else None
run = Run(" baseline ", metrics=[0.9, 0.52, 0.61])
print(repr(run.name))
print(run.best_loss)
print(Run("empty").best_loss)
try:
Run("bad", learning_rate=-1)
except ValueError as e:
print("ValueError:", e)Output:
'baseline'
0.52
None
ValueError: learning_rate must be positive, got -1
@property works on a dataclass exactly as on any class. A bad learning_rate now fails when the object is built, not three hours into training.#Frozen, Ordered and Slotted Dataclasses
@dataclass takes options. Three of them change behaviour you will care about: frozen, order and slots. A run's settings should not change once the run has started, so they get their own small class and the first option.#frozen=True: read-only and hashable
== but its fields can change, so Python refuses to hash it.from dataclasses import dataclass, replace, FrozenInstanceError
@dataclass(frozen=True)
class RunConfig:
learning_rate: float
epochs: int
seed: int = 42
def __post_init__(self) -> None:
if self.learning_rate <= 0:
raise ValueError("learning_rate must be positive")
cfg = RunConfig(0.001, 10)
try:
cfg.epochs = 20
except FrozenInstanceError as e:
print("FrozenInstanceError:", e)
cache = {cfg: "cached features"}
print(cache[RunConfig(0.001, 10)])
cfg2 = replace(cfg, seed=7)
print(cfg2)
print(cfg == cfg2)
@dataclass
class Loose:
x: int
try:
{Loose(1): "a"}
except TypeError as e:
print("TypeError:", e)Output:
FrozenInstanceError: cannot assign to field 'epochs'
cached features
RunConfig(learning_rate=0.001, epochs=10, seed=7)
False
TypeError: unhashable type: 'Loose'
dataclasses.replace(obj, field=new_value). Frozen is the right default for settings and experiment descriptions, which you want to share and cache without worrying that someone edited them.A frozen config also turns into JSON and back in two lines, which is how you save the settings of a run next to its results:
import json
from dataclasses import dataclass, asdict
@dataclass(frozen=True)
class RunConfig:
learning_rate: float
epochs: int
seed: int = 42
text = json.dumps(asdict(RunConfig(0.001, 10)))
print(text)
print(RunConfig(**json.loads(text)))Output:
{"learning_rate": 0.001, "epochs": 10, "seed": 42}
RunConfig(learning_rate=0.001, epochs=10, seed=42)
__post_init__ of a frozen class, self.total_steps = ... is also an assignment, so it raises too.This frozen config should compute total_steps from the other two fields, but creating it raises FrozenInstanceError. Fix it so the last line prints 3000 and the class stays frozen.
3000
#order=True: sortable records
order=True, the decorator adds <, <=, > and >=. It compares the fields as a tuple, left to right. Use field(compare=False) to leave a field out of the comparison. Here a finished Run is ranked by its loss.from dataclasses import dataclass, field
@dataclass(order=True)
class Run:
loss: float
name: str = field(compare=False)
learning_rate: float = field(compare=False, default=0.001)
runs = [
Run(0.45, "wide"),
Run(0.31, "baseline"),
Run(0.38, "small"),
]
for run in sorted(runs):
print(run.name, run.loss)
print(min(runs).name)Output:
baseline 0.31
small 0.38
wide 0.45
baseline
loss takes part in the ordering here, so sorted lists the lowest loss first. If two fields took part, the second would only break ties in the first. Put the field you care about most on top.#slots=True: no per-object dictionary
__dict__, a small dictionary holding its attributes. That is what lets you add new attributes at any time, and it costs memory. With slots=True (Python 3.10 and later), the class stores its attributes in a fixed layout instead and has no __dict__.tracemalloc, the standard-library tool that reports memory Python has allocated, and prints only how the two classes compare, because the byte counts differ from machine to machine.import tracemalloc
from dataclasses import dataclass
@dataclass
class RunDict:
loss: float
accuracy: float
@dataclass(slots=True)
class RunSlots:
loss: float
accuracy: float
def bytes_per_instance(cls, n=100_000):
tracemalloc.start()
before = tracemalloc.get_traced_memory()[0]
items = [cls(0.5, 0.9) for _ in range(n)]
after = tracemalloc.get_traced_memory()[0]
tracemalloc.stop()
return (after - before) / n
with_dict = bytes_per_instance(RunDict)
with_slots = bytes_per_instance(RunSlots)
print("slots use less memory:", with_slots < with_dict)
print("saving is over a quarter:", with_slots < 0.75 * with_dict)
p = RunSlots(0.5, 0.9)
print(hasattr(RunDict(0.5, 0.9), "__dict__"), hasattr(p, "__dict__"))
try:
p.epochs = 10
except AttributeError:
print("AttributeError: no new attributes")Output:
slots use less memory: True
saving is over a quarter: True
True False
AttributeError: no new attributes
with_dict and with_slots. For two floats, CPython 3.12 on a 64-bit desktop gives about 88 against 56 bytes (a saving of about 36 percent) and 3.13 gives about 96 against 56 (about 42 percent). In the browser, where pointers are 4 bytes, the numbers are smaller, about 48 against 28, and the saving is similar. Treat all of these as example measurements, not constants. The test counts only the instance and its dictionary: the 0.5 and 0.9 floats are shared constants, so they cost nothing per object.slots=True after you have measured a problem, not before.#Enum: Names Instead of Magic Strings
Run was a loose string. An Enum is a class whose instances are a fixed, named set of choices. You define the members once, and from then on code refers to Status.RUNNING instead of retyping "running".from enum import Enum
class Status(Enum):
PENDING = "pending"
RUNNING = "running"
DONE = "done"
FAILED = "failed"
print(Status.RUNNING)
print(Status.RUNNING.name, Status.RUNNING.value)
print(Status("done"))
print(list(Status))
try:
Status.RUNING
except AttributeError as e:
print("AttributeError:", e)
try:
Status("finished")
except ValueError as e:
print("ValueError:", e)Output:
Status.RUNNING
RUNNING running
Status.DONE
[<Status.PENDING: 'pending'>, <Status.RUNNING: 'running'>, <Status.DONE: 'done'>, <Status.FAILED: 'failed'>]
AttributeError: type object 'Status' has no attribute 'RUNING'
ValueError: 'finished' is not a valid Status
name (the identifier) and a value (what you stored). You can build a member from a value with Status("done"), which is how you turn text from a file or API back into a member, and a bad value raises ValueError immediately.Compare that with strings:
status = "runing" # typo
if status == "running":
print("running")
else:
print("silently not running")Output:
silently not running
Status.RUNING typo is an attribute that does not exist, so it fails on the line that contains it. That is most of the benefit: a quiet wrong answer becomes a loud error at the place you made the mistake. A type checker adds a second layer, since a function that declares status: Status will not accept a loose string.#StrEnum: members that are also strings
Enum, Status.DONE == "done" is False, and json.dumps cannot encode a member. When the members stand for strings that cross a boundary (a JSON file, an API response, a database column), use StrEnum (Python 3.11 and later). Each member is a real str.import json
from enum import Enum, StrEnum
class Plain(Enum):
DONE = "done"
class Status(StrEnum):
PENDING = "pending"
RUNNING = "running"
DONE = "done"
FAILED = "failed"
print(Plain.DONE == "done")
print(Status.DONE == "done")
print(json.dumps({"status": Status.DONE}))
print(f"job is {Status.RUNNING}")
try:
json.dumps({"status": Plain.DONE})
except TypeError as e:
print("TypeError:", e)Output:
False
True
{"status": "done"}
job is running
TypeError: Object of type Plain is not JSON serializable
auto() assigns values for you when you only care about the names, and IntEnum makes members behave as integers, which suits status codes. For everything in this lesson, Enum and StrEnum are enough.#An Enum for the legal status changes
Run from the dataclass sections can carry a status of its own.from dataclasses import dataclass
from enum import StrEnum
class Status(StrEnum):
PENDING = "pending"
RUNNING = "running"
DONE = "done"
FAILED = "failed"
ALLOWED = {
Status.PENDING: {Status.RUNNING, Status.FAILED},
Status.RUNNING: {Status.DONE, Status.FAILED},
Status.DONE: set(),
Status.FAILED: {Status.PENDING},
}
@dataclass
class Run:
name: str
status: Status = Status.PENDING
def advance(self, new: Status) -> None:
if new not in ALLOWED[self.status]:
raise ValueError(f"cannot go from {self.status.value} to {new.value}")
self.status = new
run = Run("baseline")
run.advance(Status.RUNNING)
print(run.status)
try:
run.advance(Status.PENDING)
except ValueError as e:
print("ValueError:", e)Output:
running
ValueError: cannot go from running to pending
if statements scattered through the code.#Protocol: Duck Typing That a Checker Can Read
Runs now have a record and a status. The last job is ranking them: which run is best? That depends on what "best" means, and different projects will want different scorers.
scorer.score(run) works with any object that has a score method, whatever its class. That is flexible, but nothing tells a reader or a tool which methods the function needs. An abstract base class (from the previous lesson) fixes that by making every implementation inherit from it, which you cannot do to a class you do not own.from dataclasses import dataclass
from typing import Protocol
@dataclass
class Run:
name: str
loss: float
accuracy: float
class Scorer(Protocol):
"""Anything with a score(run) method that returns a float. Higher is better."""
def score(self, run: Run) -> float: ...
class LowLoss:
def score(self, run: Run) -> float:
return -run.loss
class HighAccuracy:
def score(self, run: Run) -> float:
return run.accuracy
def best_run(runs: list[Run], scorer: Scorer) -> Run:
return max(runs, key=scorer.score)
runs = [
Run("baseline", 0.45, 0.87),
Run("wide", 0.31, 0.89),
Run("deep", 0.38, 0.92),
]
print(best_run(runs, LowLoss()).name)
print(best_run(runs, HighAccuracy()).name)Output:
wide
deep
Scorer. The ... in the protocol body is real Python: it means "no code here, only the signature".Scorer hint. The check is done by a type checker, a separate program such as mypy or pyright that reads your annotations without running the code. Pass it a class that does not match and it reports the problem. For a class with rate instead of score, mypy reports:error: Argument 2 to "best_run" has incompatible type "NoScore"; expected "Scorer" [arg-type]
AttributeError: 'NoScore' object has no attribute 'score'. Nothing in the runnable cells on this page runs a type checker, so you will not see the first message here. In your editor and in CI you can.#runtime_checkable checks names only
isinstance. Adding @runtime_checkable allows it, but the check is shallow: it only tests that the methods exist.from dataclasses import dataclass
from typing import Protocol, runtime_checkable
@dataclass
class Run:
name: str
@runtime_checkable
class Scorer(Protocol):
def score(self, run: Run) -> float: ...
class Ok:
def score(self, run: Run) -> float:
return 1.0
class WrongSignature:
def score(self, run: Run, extra: int) -> float:
return 0.0
class Missing:
def rate(self, run: Run) -> float:
return 0.0
for obj in (Ok(), WrongSignature(), Missing(), "a string"):
print(type(obj).__name__, isinstance(obj, Scorer))Output:
Ok True
WrongSignature True
Missing False
str False
WrongSignature passes isinstance even though calling score(run) on it would fail. Only the type checker compares signatures. Treat isinstance against a protocol as a convenience for "does this have the method at all", not as validation.You accept objects from a library you cannot edit, and each must have a fit(X, y) method. Which tool describes that requirement without touching the library?
#Choosing Between Dataclass, Plain Class, NamedTuple and Pydantic
Run. Before you pick it everywhere, compare it with the other ways to hold named fields. All four can do it, and they differ in what they check and what they cost.| Plain class | @dataclass | NamedTuple | Pydantic model | |
|---|---|---|---|---|
| Writing it | You write every method | Field list only | Field list only | Field list only |
| Mutable | Yes | Yes (or frozen=True) | No | Yes (or frozen) |
| Behaves like a tuple (unpack, index) | No | No | Yes | No |
| Checks types of the values | No | No | No | Yes, and converts where it can |
| Methods and properties | Yes | Yes | Yes | Yes |
| Comes with Python | Yes | Yes | Yes | No, a package to install |
| Best for | Behaviour with some state | Internal records, configs | Small fixed rows, tuple results | Data arriving from outside |
The row that surprises people is the type check. A dataclass annotation is documentation and input for a type checker, not a runtime guard:
from dataclasses import dataclass
@dataclass
class Run:
name: str
learning_rate: float
r = Run("baseline", learning_rate="fast")
print(r)Output:
Run(name='baseline', learning_rate='fast')
learning_rate: float says a number. That is fine for your own code, where the type checker watches you. It is not fine for data from a request body or a file you did not write, and that is the job Pydantic does: it validates and converts values when the object is created. The lesson on building APIs with FastAPI introduces it. Its models are written with the same annotated-field style you have just learned, so the step from dataclass to Pydantic is small.NamedTuple when you want tuple behaviour such as unpacking, a plain class when behaviour matters more than data, and Pydantic at the edges where untrusted data comes in.#Common Mistakes
#Try It Yourself
Task is a unit of work like a Run: a dataclass record, a Status enum and a Protocol-typed notifier. Fill in the Task dataclass so the calls at the bottom produce the expected output.Tests: Expected output: notify: train-bert: running, then notify: train-bert: done, then Task(name='train-bert', status=<Status.DONE: 'done'>, attempts=1, tags=[]), then ValueError: cannot go from done to running, then ValueError: name must not be empty.
Task hashable by freezing it, and notice what breaks (hint: advance assigns fields, so it needs to return a new task with replace). Then write a second notifier class that appends messages to a list, and pass it in without changing Task at all.#Going Further
@dataclass generates for you and shows how to write your own. For the other uses of __slots__, including inheritance rules, see the Python documentation on the data model.#Recap
__init__, __repr__ and __eq__. Mutable defaults need field(default_factory=...), and validation or derived values go in __post_init__.frozen=True makes instances read-only and hashable. order=True makes them sortable by the fields that take part in the comparison. slots=True removes the per-object dictionary, which saved about 36 to 42 percent of the memory of a two-float object in the example measurements, at the cost of fixing the attribute list.Status(...) raises ValueError. StrEnum is the version whose members are also strings.runtime_checkable only tests that method names exist. Dataclass annotations are also not enforced at runtime, which is the gap Pydantic fills for data from outside.#Quick Check
What does this print? @dataclass class P: x: int try: seen = {P(1)} except TypeError: print('TypeError') else: print('ok')