Level 0: Foundation
★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.Labels that say what goes where
Imagine a parts bin labelled “M3 screws” versus an unlabelled one. The labels don’t stop you putting a bolt in the wrong bin, but they make mistakes easy to spot, for you, for your teammates, and for automatic checkers. Type hints are those labels for Python code: mass: float, names: list[str]. Dataclasses use those labels to build tidy record types automatically: write the fields once and Python generates the constructor, printing and comparison code for you.
@dataclass
class Point:
x: float
y: float
z: float = 0.0| p.x = 5 | allowed |
| p == Point(1, 2, 3) | compares fields |
| {p: "label"} (hashable?) | TypeError: unhashable |
| sorted([p, q]) | TypeError: < not supported |
| p.extra = 1 | allowed (typo-prone!) |
| bytes per point | ≈ 168 |
Mission software mixes units, frames and data formats; mixing them up has destroyed spacecraft (the Mars Climate Orbiter’s pound-force vs newton error). Typed, validated records for states, commands and telemetry, checked in CI by mypy or pyright, catch whole classes of such errors early and make research code readable months later.
- 1. Python type hints are checked…
- 2. A dataclass saves you from writing…
- 3. `mass: float` is…
Level 1: Beginner
★★☆☆☆ Basic⏱ 25 minSecondary-school mathematics: arithmetic and elementary algebra.Annotating functions and variables
def burn(state: "SpacecraftState", dv_mps: float, isp_s: float = 300.0) -> "SpacecraftState": ...
names: list[str] = []
calib: dict[str, float] | None = None # Python ≥ 3.10 union syntax (= Optional[...])Built-in generics (list[int], dict[str, float], tuple[float, float]) work since Python 3.9. Annotations are stored in __annotations__. With from __future__ import annotations they are kept as strings, which allows forward references.
A first dataclass
from dataclasses import dataclass, field
@dataclass
class Reading:
sensor: str
value: float
flags: list[str] = field(default_factory=list) # never use a bare [] defaultReading("imu", 1.2) works, prints as Reading(sensor='imu', value=1.2, flags=[]), and compares field by field.
- 1. Correct annotation for an optional calibration table:
- 2. Why field(default_factory=list)?
- 3. Does `x: int = 'hello'` raise an error at runtime?
Level 2: Intermediate
★★★☆☆ Intermediate⏱ 35 minUndergraduate students and practising engineers.Dataclass options
| option | effect |
|---|---|
frozen=True |
assignment raises FrozenInstanceError; with eq, generates __hash__ |
order=True |
<, <=, >, >= by comparing field tuples in order |
slots=True |
__slots__: no per-instance __dict__, less memory, typo-proof attributes |
kw_only=True |
all fields keyword-only |
field(compare=False, repr=False) |
exclude a field from comparisons / repr |
__post_init__ runs after the generated __init__, so put validation or derived fields there. dataclasses.replace(obj, **changes) copies with changes (the idiom for frozen objects), and asdict / astuple convert recursively.
More typing tools
Literal["safe", "nominal"]: only these values.TypedDict: typed dict shapes (e.g. JSON).Protocol: structural typing. Any class with the right methods qualifies (“duck typing, checked”).TypeVar/ generics (def first[T](xs: list[T]) -> Tin 3.12).Callable[[float], float],Iterator[int].
- 1. With order=True, Task(1, 'b') < Task(2, 'a') because…
- 2. To change a field of a frozen dataclass you…
- 3. A Protocol type accepts…
Level 3: Advanced
★★★★☆ Advanced⏱ 35 minGraduate level, with full derivations and proofs.Why eq without frozen kills hashing
If two objects compare equal they must have equal hashes, and a dict assumes a key’s hash never changes. A mutable object compared by value could change after insertion and become unfindable. So @dataclass (eq=True, frozen=False) sets __hash__ = None, making instances unhashable. frozen=True restores a field-based hash.
Gradual typing and soundness
Python’s typing is gradual: Any is compatible with everything, and unannotated code is unchecked. Static checkers find many bugs (wrong argument types, None not handled, missing attributes), but annotations aren’t enforced at runtime. Libraries like pydantic or beartype add runtime validation where data crosses trust boundaries (files, networks, user input).
Variance in one line
list[int] is not a subtype of list[float], because a function taking list[float] could append a float to your int list. Read-only containers (Sequence[int]) are covariant: Sequence[int] is a Sequence[float].
- 1. Default @dataclass instances are…
- 2. Is list[int] a subtype of list[float] for a type checker?
- 3. Where is runtime validation most valuable?
Level 4: Expert
★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.Types and memory, measured
Exercise 2. A ~20-line runtime checker built on typing.get_type_hints, get_origin and get_args correctly flags a string passed as a float, a list of ints passed as list[str], a wrongly-typed value inside an Optional[dict[str, float]], and True passed where a float was annotated (bools are ints in Python, a classic gotcha).
Memory per 3-float point, including the three float objects (CPython 3.12):
| representation | bytes per point |
|---|---|
@dataclass(slots=True) |
128 |
| tuple | 136 |
@dataclass |
168 |
| dict | 256 |
In Pyodide (32-bit WebAssembly, smaller pointers and objects) the same measurement gives 76, 80, 96 and 156 bytes, the same ranking. Slots save about a quarter of the memory of a regular dataclass, which matters for millions of particles or waypoints. For real numeric bulk data, use NumPy arrays (C1.5) at 24 bytes per point.
In AI, robotics and aerospace
- Typed state and command records with units in field names (
mass_kg,dv_mps) reduce unit errors. - Frozen dataclasses as configuration objects for experiments, hashable for caching.
- mypy / pyright in CI for ground software and research codebases.
- Runtime validation of telemetry packets and configuration files at system boundaries.
References
- PEP 484 (type hints), PEP 557 (data classes), PEP 544 (protocols), PEP 604 (X | Y unions), PEP 695 (type parameter syntax).
- Python documentation:
typinganddataclassesmodules. - J. Lehtosalo et al. mypy documentation (mypy.readthedocs.io).
- L. Ramalho (2022). Fluent Python, 2nd ed. O’Reilly (chapters 5, 8, 15).
- NASA (1999). Mars Climate Orbiter Mishap Investigation Board Phase I Report.