Foundations to Frontier
Tests
C. Programming, Tools and HPC › C1 Python for Science

Type Hints and Dataclasses

Type hints document what a function expects and returns (def burn(dv: float) -> State) and let static checkers like mypy and pyright catch bugs before the code runs. Dataclasses turn annotated classes into full-featured records with generated __init__, __repr__, equality, ordering, hashing and immutability. This topic covers the typing toolkit (generics, Optional/Union, Protocol, TypedDict, Literal), the dataclass options (field, default_factory, __post_init__, frozen, order, slots, replace, asdict) and their pitfalls. In the exercises you model spacecraft state with validated, immutable dataclasses, then write a small runtime type checker and measure the memory cost of dataclasses, slots and dicts.

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.

What does @dataclass write for you?
@dataclass
class Point:
    x: float
    y: float
    z: float = 0.0
generated: __init____repr____eq__
p.x = 5allowed
p == Point(1, 2, 3)compares fields
{p: "label"} (hashable?)TypeError: unhashable
sorted([p, q])TypeError: < not supported
p.extra = 1allowed (typo-prone!)
bytes per point≈ 168
Type annotations (x: float) declare the fields; the decorator reads them and writes the boilerplate. Note the subtle rule: eq=True without frozen=True sets __hash__ to None (mutable objects that compare by value must not be hashable, or a dict would lose them after a change). frozen=True makes instances immutable and hashable; slots=True removes the per-instance __dict__, saving memory and catching attribute typos.
Why engineers care

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.

📝 Quick check (Level 0)
0/3 answered
  1. 1. Python type hints are checked…
  2. 2. A dataclass saves you from writing…
  3. 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 [] default

Reading("imu", 1.2) works, prints as Reading(sensor='imu', value=1.2, flags=[]), and compares field by field.

📝 Quick check (Level 1)
0/3 answered
  1. 1. Correct annotation for an optional calibration table:
  2. 2. Why field(default_factory=list)?
  3. 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]) -> T in 3.12).
  • Callable[[float], float], Iterator[int].
🐍 Exercise 1: typed, validated spacecraft records
Write a frozen, hashable Vec3 dataclass; a SpacecraftState dataclass with a per-instance events list, __post_init__ validation and a burn() method (Tsiolkovsky) that returns a new state via replace(); and an order=True Task dataclass whose payload is excluded from comparisons, used to schedule tasks.
📝 Quick check (Level 2)
0/3 answered
  1. 1. With order=True, Task(1, 'b') < Task(2, 'a') because…
  2. 2. To change a field of a frozen dataclass you…
  3. 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].

📝 Quick check (Level 3)
0/3 answered
  1. 1. Default @dataclass instances are…
  2. 2. Is list[int] a subtype of list[float] for a type checker?
  3. 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.

🐍 Exercise 2 (research): a runtime type checker, and the memory of records
Implement check_type for int, float, str, bool, list[T], dict[K, V] and Optional/Union, use it to validate dataclass instances field by field, then measure bytes per instance for a dataclass, a slots dataclass, a dict and a tuple holding three floats.

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

  1. PEP 484 (type hints), PEP 557 (data classes), PEP 544 (protocols), PEP 604 (X | Y unions), PEP 695 (type parameter syntax).
  2. Python documentation: typing and dataclasses modules.
  3. J. Lehtosalo et al. mypy documentation (mypy.readthedocs.io).
  4. L. Ramalho (2022). Fluent Python, 2nd ed. O’Reilly (chapters 5, 8, 15).
  5. NASA (1999). Mars Climate Orbiter Mishap Investigation Board Phase I Report.