Modern scientific Python: data model, types and dataclasses
A dense review of Python idioms most important in numerical code (data-model protocols, generators, context managers, decorators), followed by what distinguishes maintainable research code: type annotations checked statically, immutable dataclasses for configurations and results, and array shape annotations that catch dimensional errors.
After this lesson you can
- Explain using the data model why constructs such as with torch.no_grad() or a loop over a DataLoader work as they do.
- Use generators and context managers to stream data and manage resources and temporary modes.
- Write decorators adding measurement, caching, or validation while preserving function identity.
- Annotate numerical code with generics, Protocol, and Literal and check it with mypy or pyright.
- Model experiment configurations with validated immutable dataclasses and annotate array shapes with jaxtyping.
Motivation: code that keeps changing
Research code is not written once: it is rewritten every week. You change architecture, add a loss term, try another normalization, or rename a hyperparameter. Each change offers opportunities for three errors that break nothing visibly but spoil everything:
- A configuration as a loose dictionary. You write
cfg["lerning_rate"] = 1e-3with a typo. Python creates a new key, training keeps the old rate, and you spend an afternoon comparing curves that should not look alike. - An exhausted iterator. You pass the same validation-example generator to two metrics. The second gets an empty sequence, returns
0ornan, and the report prints it without complaint. - Two swapped axes. A tensor of shape
(batch, dim)arrives transposed at a function using broadcasting (automatic expansion of size-1 axes, covered in broadcasting rules). Ifbatch == dim, there is no shape error: only a model that learns worse.
Python does not protect you from these by default, but provides tools for code to state expectations explicitly and for a machine to check them. This lesson follows those tools in dependency order. First the data model, explaining why for, with, and model(x) work as they do. Then generators for constant-memory streams and decorators to add behavior without changing code. Next come statically checked types, immutable dataclasses for configurations, and array shape annotations. We finish by asking when pure Python stops being enough.
This is not a Python-from-scratch course: we assume you can write functions, classes, and comprehensions. The goal is to understand mechanisms, not memorize syntax, because mechanisms let you read PyTorch code and write your own with similar robustness.
The data model: syntax is sugar over special methods
When you write for x in data, len(ds), a @ b, or with open(p) as f, Python does nothing magical: it translates each construct into a call to a special method (also called dunder for double underscores) on the object’s type. Any class defining those methods participates in language syntax as if native.
The table summarizes protocols most common in numerical code:
| You write | Python executes | Where you will see it |
|---|---|---|
for x in obj | it = type(obj).__iter__(obj) then type(it).__next__(it) until StopIteration | DataLoader, files, generators |
with mgr as v | v = type(mgr).__enter__(mgr); on exit, always, type(mgr).__exit__(mgr, tipo, exc, tb) | torch.no_grad(), open, timers |
obj(x) | type(obj).__call__(obj, x) | nn.Module, loss functions, decorators |
obj.a, obj.a = v | __getattribute__, and __getattr__ on failure; __setattr__ | parameter registration in nn.Module |
len(obj), obj[i] | __len__, __getitem__ | PyTorch Dataset |
a + b, a @ b | __add__/__radd__, __matmul__/__rmatmul__ | arrays, tensors, polynomials |
repr(obj), a == b, hash(a) | __repr__, __eq__, __hash__ | debugging, dictionary keys |
Two details in this table explain much behavior that would otherwise seem arbitrary.
Iterable is not the same as iterator. An iterable has __iter__, returning an iterator; an iterator has __next__ (and __iter__ returning itself). A list or DataLoader is iterable: each for requests a new iterator, so you can traverse it repeatedly. A generator is an iterator: once traversed it is exhausted.
__exit__ always runs. If a with body raises an exception, __exit__ receives it as an argument before propagation; returning a truthy value suppresses it. Thus with torch.no_grad(): restores gradient mode even if evaluation fails midway, making it the right way to manage resources or temporary modes: files, locks, seeds, and global options.
with with and without an exception: gradient mode is restored in both. In model.w = ..., notice __getattr__ enters only when ordinary lookup fails.With these pieces you can write in twenty lines the skeleton of what nn.Module does: intercept assignments to register parameters, retrieve them with __getattr__, and wrap forward in __call__ that runs hooks. This is PyTorch’s mechanism without the details.
class Parameter:
def __init__(self, value):
self.value = value
def __repr__(self):
return f"Parameter({self.value!r})"
class Module:
"""Esqueleto de nn.Module: registra parámetros al asignarlos y envuelve forward en __call__."""
def __init__(self):
object.__setattr__(self, "_parameters", {}) # sin pasar por nuestro __setattr__
object.__setattr__(self, "_hooks", [])
def __setattr__(self, name, value):
if isinstance(value, Parameter):
self._parameters[name] = value # se registra y NO va a __dict__
else:
object.__setattr__(self, name, value)
def __getattr__(self, name): # solo se llama si la búsqueda normal falla
params = self.__dict__["_parameters"]
if name in params:
return params[name]
raise AttributeError(f"{type(self).__name__!r} no tiene el atributo {name!r}")
def __call__(self, *args):
out = self.forward(*args)
for hook in self._hooks:
hook(self, args, out)
return out
def parameters(self):
return list(self._parameters.values())
class Affine(Module):
def __init__(self, w, b):
super().__init__()
self.w = Parameter(w)
self.b = Parameter(b)
self.name = "afín" # no es un Parameter: atributo normal
def forward(self, x):
return self.w.value * x + self.b.value
m = Affine(2.0, 1.0)
m._hooks.append(lambda mod, args, out: print(f"hook: {type(mod).__name__}{args} -> {out}"))
print("m(3.0) =", m(3.0))
print("parámetros:", m.parameters())
print("¿'w' en m.__dict__?", "w" in m.__dict__, "| m.w =", m.w)
m.__dict__["__len__"] = lambda: 99 # en la instancia: len() lo ignora
try:
len(m)
except TypeError as e:
print("len(m):", e)The last line illustrates type lookup: a __len__ placed on the instance does not count because len consults type(m). Now the context protocol, with a homemade no_grad, and iteration protocol, with a loader that like DataLoader is iterable rather than an iterator:
_GRAD_ENABLED = True # en PyTorch es un estado por hilo
class no_grad:
def __enter__(self):
global _GRAD_ENABLED
self.prev, _GRAD_ENABLED = _GRAD_ENABLED, False
def __exit__(self, exc_type, exc, tb):
global _GRAD_ENABLED
_GRAD_ENABLED = self.prev # se restaura SIEMPRE, también si hubo excepción
return False # False: la excepción, si la hay, se propaga
try:
with no_grad():
print("dentro del with:", _GRAD_ENABLED)
raise RuntimeError("fallo a mitad de la evaluación")
except RuntimeError as e:
print("excepción propagada:", e)
print("después del with:", _GRAD_ENABLED)
class Loader:
"""Iterable, como DataLoader: cada for llama a __iter__ y obtiene un iterador nuevo."""
def __init__(self, data, batch_size):
self.data, self.batch_size = data, batch_size
def __len__(self):
return -(-len(self.data) // self.batch_size) # división hacia arriba
def __iter__(self):
for i in range(0, len(self.data), self.batch_size):
yield self.data[i:i + self.batch_size]
loader = Loader(list(range(7)), batch_size=3)
it = iter(loader) # lo que hace el for por dentro
while True:
try:
batch = next(it)
except StopIteration:
break
print("lote", batch)
print("len(loader) =", len(loader))
print("dos épocas sobre el iterable:", [sum(len(b) for b in loader) for _ in range(2)])
gen = iter(loader)
print("dos pasadas sobre el iterador:", [sum(len(b) for b in gen) for _ in range(2)])The last line is the motivation’s second error in miniature: the first pass over the iterator counts all 7 elements and the second counts 0, without warning.
Generators and lazy pipelines
A generator is the cheapest way to write an iterator: a function with yield. Calling it executes nothing; it returns a generator object. Each next resumes the function until the next yield, delivers that value, and freezes the execution frame (locals, exact code location) until the next request.
The difference from a list is not syntax but execution order. [parse(l) for l in lines] parses every line before delivering the first; (parse(l) for l in lines) parses none until someone requests an element, then parses only that one. In a multistage pipeline, this determines memory requirements.
Proof
Lazy case. The consumer requests an element from ; to produce it, that stage requests elements from and so on to the source. Each stage stores only its current element in its frozen frame: when it yields and resumes, the local variable is reassigned and the previous element is no longer referenced. No stage stores delivered elements, so at any instant there is at most one per stage plus bounded consumer state.
Eager case. The list from contains its elements immediately after construction, and all remain referenced by the list. Since it is built in full before yielding anything, no later stage receives an element before has consumed everything upstream.
∎The second half of the eager case is often surprising: it costs memory and breaks interleaving. One eager stage inside a lazy pipeline is enough to make all preceding work execute in blocks.
sorted: some operations need all data.What you should have seen:
- With everything lazy, the trace is a staircase. Each file line goes through all stages before the next is read, and the aggregator gets its first datum at step 4 (or later if initial lines fail the filter). Filtered lines do not reach the aggregator.
- A list in
parsearturns the staircase into blocks. All lines are read and parsed first, then filtered; the aggregator waits until the end. Peak memory is and grows with the file: with 20 GB of data, that peak is the whole file as Python objects, several times larger than original text. - Lists accumulate. Each list is bound to a name (
lines,records,valid) and remains alive while that name exists even if nobody will traverse it again: with two or three eager stages, peak is their sum. In one nested expression each intermediate list would be released once the next is built, but both coexist during construction. sortedis inherently eager. It cannot return the smallest element without seeing all of them. No generator trick makes it lazy: sorting 20 GB needs another algorithm (external block sorting or top- with a heap of size ).
The quietest error: consuming twice
An exhausted generator raises no error when traversed again: it simply yields nothing. sum(g) on a consumed generator is 0, list(g) is [], and a for loop never executes its body. Rule of thumb: if a sequence will be traversed more than once, pass an iterable (list, Dataset, object with __iter__), not an iterator; or pass a function creating a new generator each call.
yield from and generators receiving values
Two extensions complete the protocol. yield from sub delegates to another iterable, yielding all its elements as if written in the outer generator, naturally chaining sources (files or dataset fragments). A generator can also receive values with send: x = yield y yields y and waits for the next sent value. This underlies coroutines, useful for stateful accumulators.
import itertools
def read_shard(name, n):
for i in range(n):
yield f"{name}:{i}"
def read_all(shards):
for name, n in shards:
yield from read_shard(name, n) # delega: entrega todo lo de cada fragmento
print(list(read_all([("a", 2), ("b", 3)])))
print(list(itertools.islice(read_all([("a", 10**9)]), 3))) # perezoso: solo genera 3 de mil millones
print(list(itertools.batched(range(7), 3))) # lotes (Python ≥ 3.12)
def running_mean():
total, n, mean = 0.0, 0, None
while True:
x = yield mean # entrega la media y espera el siguiente valor
total, n = total + x, n + 1
mean = total / n
avg = running_mean()
next(avg) # «cebar»: avanzar hasta el primer yield
print([avg.send(x) for x in [2.0, 4.0, 9.0]])Laboratory: a large CSV with constant memory
Now measure for real. Generate a synthetic sensor-reading CSV, process it both ways (all lists or all generators), and measure peak memory with tracemalloc, which records interpreter memory allocations. The browser limits experiment size to tens of thousands of rows; what matters is how each version scales when quadrupling the file.
import random, tracemalloc, time
def make_csv(path, n, seed=0):
rng = random.Random(seed)
with open(path, "w") as f:
f.write("id,sensor,value,ok\n")
for i in range(n):
f.write(f"{i},s{rng.randrange(8)},{rng.gauss(0, 1):.6f},{int(rng.random() < 0.9)}\n")
def parse(line):
i, sensor, value, ok = line.split(",")
return int(i), sensor, float(value), ok.strip() == "1"
def mean_eager(path):
with open(path) as f:
lines = f.readlines()[1:] # todo el fichero en una lista
records = [parse(l) for l in lines] # otra lista, más pesada
valid = [r for r in records if r[3]]
return sum(r[2] for r in valid) / len(valid)
def mean_lazy(path):
with open(path) as f:
next(f) # saltar la cabecera
records = (parse(l) for l in f)
valid = (r for r in records if r[3])
total = count = 0
for r in valid:
total += r[2]
count += 1
return total / count
def peak_mib(fn, *args):
tracemalloc.start()
out = fn(*args)
peak = tracemalloc.get_traced_memory()[1]
tracemalloc.stop()
return out, peak / 2**20
for n in (10_000, 40_000):
make_csv("/tmp/sensores.csv", n)
(m1, p1), (m2, p2) = peak_mib(mean_eager, "/tmp/sensores.csv"), peak_mib(mean_lazy, "/tmp/sensores.csv")
print(f"N = {n:6d} listas: {p1:6.2f} MiB generadores: {p2:5.3f} MiB (media {m1:.5f} = {m2:.5f})")Both versions calculate the same mean. The list version quadruples memory when quadruples and occupies about seven times the file itself (the 40,000-row CSV occupies 0.8 MiB): each textual number became a Python object with a header inside a tuple inside a list. The generator version stays at the same fraction of a MiB, the read buffer and one record in progress. With a 20 GB file, the first would need over one hundred GB of RAM; the second processes it in the same fraction of a MiB at disk speed.
Text in Python: Unicode, regular expressions, and counts
Text data runs throughout the course, from training logs parsed for curves to your GPT tokenizer. Three ideas prevent common mistakes.
Length depends on what you count. len("café") is 4 code points, but len("café".encode("utf-8")) is 5 bytes because “é” uses two. There are two ways to write “é”: one code point (U+00E9), or “e” followed by a combining accent (U+0301). They look identical but are not equal under == or the same length. NFC normalization composes characters and NFD decomposes them; normalize before comparing or counting.
Regular expressions are compiled once and written as raw strings. re.compile(r"\d+") prevents \d being interpreted as a Python escape. findall gets all matches, finditer objects with positions, and named groups such as (?P<loss>...) extract readable fields.
Counter is a counting dictionary. Counter(tokens).most_common(k) gives the most frequent keys, and two counters add and subtract as multisets.
import re, unicodedata
from collections import Counter
s1 = "café" # «é» precompuesta, U+00E9
s2 = "café" # «e» + acento combinante, U+0301
print(s1 == s2, len(s1), len(s2), "| tras NFC:", unicodedata.normalize("NFC", s2) == s1)
print("bytes UTF-8 de 'café':", list(s1.encode("utf-8")))
print("Straße".lower(), "|", "Straße".casefold()) # casefold: comparación sin mayúsculas, ß -> ss
text = """El 3 de mayo el modelo GPT-2 obtuvo 0.92 de exactitud; el 4 de mayo, 0.95.
¿Mejora real o ruido? Repetimos con 5 semillas: 0.93, 0.94, 0.95, 0.92 y 0.94."""
TOKEN = re.compile(r"\d+(?:\.\d+)?|\w+(?:-\w+)*|[^\w\s]")
tokens = TOKEN.findall(text.lower())
print(tokens[:12])
print(Counter(t for t in tokens if t.isalpha()).most_common(4))
scores = [float(x) for x in re.findall(r"\b0\.\d+\b", text)]
print("exactitudes:", scores, "media:", round(sum(scores) / len(scores), 4))
LOG = re.compile(r"epoch=(?P<epoch>\d+)\s+loss=(?P<loss>[\d.]+)")
log = "epoch=1 loss=2.31\nepoch=2 loss=1.87\naviso: lr muy bajo\nepoch=3 loss=1.52"
print([(int(m["epoch"]), float(m["loss"])) for m in LOG.finditer(log)])Decorators: adding behavior without changing code
Python functions are objects: they can be passed as arguments, returned, and stored in dictionaries. A decorator exploits this.
The usual pattern defines a wrapper inside the decorator that does something before and after calling the original. Without more, the resulting function is the wrapper: it is named wrapper, lacks the original documentation, and its qualified name timed.<locals>.wrapper cannot be located from the module. This breaks introspection, editor help, test messages, and pickle, which serializes functions by name. pickle is used by a multi-worker DataLoader to send functions to child processes on Windows and macOS, and on Linux since Python 3.14, whose default process start method is forkserver rather than fork.
functools.wraps(fn) fixes this: it copies fn’s name, qualified name, module, documentation, and annotations to the wrapper, updates its __dict__, and stores the original in __wrapped__.
import functools, time
def timed(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
t0 = time.perf_counter()
try:
return fn(*args, **kwargs)
finally: # se mide también si fn lanza una excepción
print(f" [{fn.__name__}: {1e3 * (time.perf_counter() - t0):.1f} ms]")
return wrapper
@timed
def loss(n):
"Suma de cuadrados: una pérdida de juguete."
return sum(i * i for i in range(n))
print(loss(200_000), "|", loss.__qualname__, "|", loss.__doc__, "|", loss.__wrapped__)
def naive(fn): # el mismo decorador, sin functools.wraps
def wrapper(*args, **kwargs):
return fn(*args, **kwargs)
return wrapper
@naive
def loss2(n):
"Esta documentación se pierde."
return n
print("sin wraps:", loss2.__qualname__, "|", loss2.__doc__) # pickle busca la función por este nombre
# registro de componentes: el decorador guarda la clase y la devuelve intacta
MODELS = {}
def register(name):
def deco(cls):
MODELS[name] = cls
return cls
return deco
@register("mlp")
class MLP: ...
@register("cnn")
class CNN: ...
print("modelos registrados:", MODELS)
# caché: lru_cache memoriza resultados por argumentos (que deben ser hashables)
calls = 0
@functools.lru_cache(maxsize=None)
def fib(n):
global calls
calls += 1
return n if n < 2 else fib(n - 1) + fib(n - 2)
print("fib(80) =", fib(80), "con", calls, "llamadas reales |", fib.cache_info())
# decorador con argumentos: tres niveles de funciones
def retry(times):
def deco(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
for attempt in range(1, times + 1):
try:
return fn(*args, **kwargs)
except IOError as e:
print(f" intento {attempt} fallido: {e}")
raise RuntimeError(f"{fn.__name__} falló {times} veces")
return wrapper
return deco
state = {"n": 0}
@retry(times=3)
def flaky_read():
state["n"] += 1
if state["n"] < 3:
raise IOError("disco ocupado")
return "datos"
print(flaky_read())Without caching, fib(n) makes calls, with , growing like the Fibonacci sequence itself (the first numerical exercise calculates exactly how much). With lru_cache it makes actual calls. The cost: the cache stores all arguments seen, which must be hashable (an np.ndarray is not) and remain alive as long as the function. Use maxsize to bound it.
Types: annotations checked before execution
Python is dynamic: a variable can hold anything and type errors appear at runtime, sometimes after hours of training. Type annotations change that without changing the language.
The system is gradual: unannotated items have type Any, compatible with everything, so you can annotate a project incrementally. Common pieces in numerical code:
- Generics.
list[float],dict[str, int],tuple[int, ...]. A generic function relates input and output types with a type variable:def first[T](xs: Sequence[T]) -> T(Python 3.12 syntax; previouslyT = TypeVar("T")). The checker knowsfirst([1, 2])is anint. - Optionals.
int | None(previouslyOptional[int]) requires checkingNonebefore use. Afterif x is not None:, the checker narrows the type tointwithin the block. - Literal.
how: Literal["mean", "sum"]permits only those strings, turning configuration typos into detectable errors. - Protocol. A protocol describes a type by its methods, not inheritance: checkable duck typing (PEP 544). Any class with
step(self) -> Nonesatisfiesclass Scheduler(Protocol): def step(self) -> None: ...without inheriting from anything. - Callable.
Callable[[float], float]for functions passed as arguments, such as an activation or learning-rate scheduler.
A key detail: mutable containers are invariant. A function accepting list[float] does not accept list[int], even though every int is valid where float is expected. Otherwise it could call xs.append(0.5) and the caller’s integer list would contain a float. mypy explains this in its message ("list" is invariant) and suggests Sequence[float], which is read-only and therefore covariant: it safely accepts list[int].
from typing import Protocol, Sequence, runtime_checkable
def scale(x: float, k: int) -> float:
return x * k
print(repr(scale("ab", 3))) # 'ababab': Python no comprueba nada
print(scale.__annotations__)
def first[T](xs: Sequence[T]) -> T: # genérico con la sintaxis de Python 3.12
return xs[0]
print(first([3, 1, 2]), first("hola"))
@runtime_checkable
class Scheduler(Protocol):
def step(self) -> None: ...
class Cosine: # no hereda de Scheduler
def step(self) -> None:
print(" lr actualizado")
class Warmup:
def step(self, epoch: int) -> None: ...
for obj in (Cosine(), Warmup(), 3):
print(type(obj).__name__, isinstance(obj, Scheduler))The last line shows a limit: isinstance with a runtime_checkable protocol checks only that a method exists, not its signature. Warmup passes at runtime even though its step requires an argument; mypy rejects it and identifies the mismatching member. That is the division of labor: the static checker reasons about signatures, runtime sees only concrete objects.
Configuration lives in pyproject.toml alongside the rest of project packaging, and should be run on each change from the editor and in repository quality automation:
[tool.mypy]
python_version = "3.12"
strict = true # sin Any implícitos, retornos comprobados, Optional estricto
warn_unreachable = true
files = ["src", "tests"]
[[tool.mypy.overrides]]
module = ["scipy.*", "sklearn.*"]
ignore_missing_imports = true # bibliotecas sin anotaciones
[tool.pyright]
typeCheckingMode = "strict"
dataclasses: configurations and results with explicit structure
Return to the motivation’s first error: configuration as a dictionary. A dictionary accepts any key, does not document fields or their types, and any function can modify it. A class with attributes solves this, but hand-writing __init__, __repr__, and __eq__ for each configuration is tedious and error-prone.
The most important detail is defaults. In a hand-written function or __init__, def __init__(self, tags=[]) evaluates [] once, when def runs, and stores the list in function defaults. All instances using the default share it. Dataclasses forbid this error: tags: list[str] = [] raises ValueError: mutable default <class 'list'> for field tags is not allowed: use default_factory on class definition (since Python 3.11, for any unhashable default).
Config; the interactive starts at the end, so go back to the beginning and step line by line. Left are names; center, Config objects; right, tags containers. With the ordinary class, the dashed red arrow comes from Config.__init__.__defaults__: the list shared by all instances. With default_factory, each object gets its own. With frozen, assignment b.lr = 3e-4 fails immediately, but a.tags.append still works: freezing is shallow. Only with a tuple is the configuration truly immutable.The third mode’s lesson bears repeating: frozen=True prevents reassigning fields, not mutating objects they reference. A truly immutable configuration uses immutable field types: tuples instead of lists, frozenset instead of set, other frozen dataclasses instead of dictionaries. To “modify” it, create a copy with dataclasses.replace(cfg, lr=3e-4), which calls __init__ again and therefore revalidates in __post_init__. A frozen dataclass with immutable fields is also hashable: it can key a results dictionary or enter an lru_cache.
What about NamedTuple or pydantic? A typing.NamedTuple is also immutable and lightweight, but it is a tuple: indexed by position, unpacked, and equal to any tuple with the same values, Point(1, 2) == (1, 2), often undesirable for configuration. pydantic goes the other way: it validates and converts types at runtime (string "3e-4" becomes float), valuable at system boundaries where YAML, JSON, or HTTP requests enter. Rule of thumb: frozen dataclasses inside code and explicit validation (pydantic or your own __post_init__) where external data enters.
Laboratory: typed experiment configuration
Design configuration for the rest of the module’s experiments: three blocks (data, model, optimization), all frozen, validated in __post_init__, converted to dictionary and JSON and reconstructed from JSON with type conversion. The missing piece, nested overrides such as optim.lr=3e-4, is yours to write in exercises.
import json, typing
from dataclasses import dataclass, field, asdict, replace, fields, is_dataclass, FrozenInstanceError
@dataclass(frozen=True, slots=True)
class DataConfig:
path: str = "data/train.bin"
seq_len: int = 256
splits: tuple[float, ...] = (0.9, 0.1)
def __post_init__(self):
if self.seq_len <= 0:
raise ValueError(f"seq_len debe ser positivo, no {self.seq_len}")
if abs(sum(self.splits) - 1) > 1e-9:
raise ValueError(f"las particiones deben sumar 1, suman {sum(self.splits)}")
@dataclass(frozen=True, slots=True)
class ModelConfig:
d_model: int = 256
n_layers: int = 4
dropout: float = 0.1
def __post_init__(self):
if not 0 <= self.dropout < 1:
raise ValueError(f"dropout debe estar en [0, 1), no {self.dropout}")
@dataclass(frozen=True, slots=True)
class OptimConfig:
lr: float = 3e-4
betas: tuple[float, float] = (0.9, 0.95)
schedule: typing.Literal["cosine", "constant"] = "cosine"
def __post_init__(self):
if self.lr <= 0:
raise ValueError(f"lr debe ser positivo, no {self.lr}")
@dataclass(frozen=True, slots=True)
class ExperimentConfig:
name: str = "baseline"
seed: int = 0
data: DataConfig = field(default_factory=DataConfig)
model: ModelConfig = field(default_factory=ModelConfig)
optim: OptimConfig = field(default_factory=OptimConfig)
def from_dict(cls, d):
"""Reconstruye una dataclass (anidada) desde un dict, convirtiendo listas a tuplas según las anotaciones."""
hints = typing.get_type_hints(cls)
kwargs = {}
for f in fields(cls):
if f.name not in d:
continue # usa el valor por defecto
tp, v = hints[f.name], d[f.name]
if is_dataclass(tp):
v = from_dict(tp, v)
elif typing.get_origin(tp) is tuple:
v = tuple(v)
kwargs[f.name] = v
unknown = set(d) - {f.name for f in fields(cls)}
if unknown:
raise KeyError(f"campos desconocidos en {cls.__name__}: {sorted(unknown)}")
return cls(**kwargs)
cfg = ExperimentConfig(name="gpt-pequeño", model=ModelConfig(d_model=384, n_layers=6))
print(cfg.model)
text = json.dumps(asdict(cfg), ensure_ascii=False)
print(text[:96], "...")
assert from_dict(ExperimentConfig, json.loads(text)) == cfg # ida y vuelta exacta
print("hashable:", hash(cfg) == hash(replace(cfg)))
for intento in (lambda: replace(cfg, optim=replace(cfg.optim, lr=-1.0)),
lambda: from_dict(ExperimentConfig, {"optim": {"lerning_rate": 1e-3}}),
lambda: setattr(cfg, "seed", 1)):
try:
intento()
except (ValueError, KeyError, FrozenInstanceError) as e:
print(f"{type(e).__name__}: {e}")The final three lines are errors a dictionary configuration would let pass: invalid value, key typo, and accidental modification. Here all three stop immediately with a message saying what and where. How this fits with configuration files, command-line overrides, and run logging is covered in configuration management.
Shapes in types: annotating array dimensions
For mypy, an array of shape (32, 64) and another of shape (64, 32) have the same type: ndarray. But most numerical code errors are shape errors: swapped axes, an extra axis, or a reduction over the wrong axis. NumPy and PyTorch broadcasting makes these silent whenever the dimensions happen to fit.
Jaxtyping’s syntax covers common cases: fixed sizes ("n 3"), named variadic axes ("*batch dim", any number of initial axes, consistent across arguments), broadcastable axes ("#dim", size dim or 1), unchecked anonymous axes ("_ dim"), and expressions ("n-1", the output of np.diff). The dtype is in the name: Float, Int, Bool, or Shaped (any).
Before using the library, let’s build the mechanism from scratch. We only need three Python pieces: typing.Annotated, which attaches metadata to a type; typing.get_type_hints, which retrieves it; and inspect.signature, which associates arguments and parameters. The decorator binds axis names in a dictionary per call.
import functools, inspect, typing
from typing import Annotated
import numpy as np
class Dims:
def __init__(self, spec):
self.names = spec.split()
def Arr(spec):
return Annotated[np.ndarray, Dims(spec)] # para mypy es un ndarray; los Dims son metadatos
def check_shapes(fn):
hints = typing.get_type_hints(fn, include_extras=True)
specs = {name: m.names for name, h in hints.items()
for m in getattr(h, "__metadata__", ()) if isinstance(m, Dims)}
sig = inspect.signature(fn)
def check(where, value, names, env):
if not isinstance(value, np.ndarray):
raise TypeError(f"{fn.__name__}: {where} debe ser ndarray, no {type(value).__name__}")
if value.ndim != len(names):
raise TypeError(f"{fn.__name__}: {where} tiene {value.ndim} ejes, se esperaban {len(names)} ({' '.join(names)})")
for axis, (name, size) in enumerate(zip(names, value.shape)):
expected = int(name) if name.isdigit() else env.setdefault(name, size)
if size != expected:
raise TypeError(f"{fn.__name__}: eje {axis} de {where} ('{name}') vale {size}, pero {name} = {expected}")
@functools.wraps(fn)
def wrapper(*args, **kwargs):
env = {} # ligaduras de esta llamada
for name, value in sig.bind(*args, **kwargs).arguments.items():
if name in specs:
check(name, value, specs[name], env)
out = fn(*args, **kwargs)
if "return" in specs:
check("la salida", out, specs["return"], env)
return out
return wrapper
@check_shapes
def attention(q: Arr("b t d"), k: Arr("b s d"), v: Arr("b s e")) -> Arr("b t e"):
w = q @ k.transpose(0, 2, 1) / np.sqrt(q.shape[-1])
w = np.exp(w - w.max(axis=-1, keepdims=True))
w /= w.sum(axis=-1, keepdims=True)
return w @ v
rng = np.random.default_rng(0)
q, k, v = rng.normal(size=(2, 5, 8)), rng.normal(size=(2, 7, 8)), rng.normal(size=(2, 7, 4))
print("salida:", attention(q, k, v).shape)
for nombre, args in [("k traspuesta", (q, k.transpose(0, 2, 1), v)),
("v con otro s", (q, k, v[:, :6])),
("q sin lote", (q[0], k, v))]:
try:
attention(*args)
except TypeError as e:
print(f"{nombre:13s} -> {e}")Each message identifies the argument, axis, and expected value at the offending call, rather than three functions later. This is the idea behind jaxtyping, which takes it much further (variadic axes, dtypes, expressions, and integration with mypy, NumPy, PyTorch, and JAX). In the course package, with development dependencies installed, the professional version of the same function is:
import torch
from jaxtyping import Float, jaxtyped
from beartype import beartype
@jaxtyped(typechecker=beartype)
def attention(q: Float[torch.Tensor, "*batch t d"],
k: Float[torch.Tensor, "*batch s d"],
v: Float[torch.Tensor, "*batch s e"]) -> Float[torch.Tensor, "*batch t e"]:
w = torch.softmax(q @ k.transpose(-2, -1) / q.shape[-1] ** 0.5, dim=-1)
return w @ v
# Para no decorar función a función, todo un paquete en las pruebas:
# from jaxtyping import install_import_hook
# with install_import_hook("atlas", "beartype.beartype"):
# import atlas
The checking cost is fixed per call, on the order of tens to a hundred microseconds (about 120 in our test with this function and small CPU tensors): negligible compared with a large matrix multiplication, but not with a loop of millions of small calls. It is usual to enable it for tests and debugging runs and disable it for long training runs.
Local lab: types and shapes in the course package
Do this lab on your machine, using the course package, because it needs tools unavailable in the browser. There are four steps:
- Add the tools as development dependencies:
uv add --dev mypy jaxtyping beartype. They are pinned inuv.lock, like the rest of the stack (dependency resolution and locking). - Copy the
[tool.mypy]section above intopyproject.tomland runuv run mypy. In an unannotated package,strict = truewill produce many warnings: start withstrict = falseand tighten it module by module with[[tool.mypy.overrides]]. - Write the annotated
attentionabove in the package and call it from a test with distinct axis sizes (batch 3, query 5, key 7, dimension 8). Then swap two axes ofkand read the error: it names the parameter (k), its actual shape, and the axis bindings already established. - Introduce the errors from the interactive below into your own code and check that each layer reacts as in the panel’s table.
The output of mypy for a type error always has the same format, fichero:línea: error: mensaje [código] (file, line, error, message, code), and the code in brackets (arg-type, return-value, index) is used to silence a specific warning with # type: ignore[código] when truly justified.
The following interactive puts the three layers up against real errors. The messages are abbreviated versions of those actually produced by mypy 2.4, jaxtyping 0.3, and beartype 0.23 on this code.
mypy before execution, runtime type and shape checking, and Python unaided. The panel's table fills in as you discover things. In error 5, change to : shape checking can no longer see it because the shapes remain consistent. No tool sees error 6.The result can be summarized in one sentence per layer:
- The static checker catches everything decidable by reading signatures: argument types, unchecked
None, strings outside aLiteral, and violated protocols. It does so before execution, across all branches, including those your tests do not visit. It cannot see shapes. - Runtime shape checking catches inconsistencies between named axes with a message identifying the offending axis. It only sees calls that execute, and only when the actual sizes reveal the error: with , swapped axes are indistinguishable.
- Nothing replaces a test of the property that matters. Normalizing along the wrong axis produces an array with the correct type, dtype, and shape. Only a check of what the function must satisfy (that each row has norm 1) detects it. This is the subject of property-based tests.
A practical trick from the second point: in tests, use sizes that are distinct and coprime for each axis (for example, batch 3, sequence 5, dimension 7). Then any axis confusion produces an inconsistent shape and is caught.
When pure Python is not enough
All of the above makes code correct and maintainable. It does not make it fast. Each Python operation on a number involves a chain of interpreter work: decoding the instruction, looking up the special method on the type (float.__mul__), creating a new object for the result (24 bytes in CPython, with its reference count and pointer to its type), and destroying intermediates. That takes tens of nanoseconds per element, compared with one or two for a compiled loop over a contiguous block of float64 values.
import time
import numpy as np
n = 200_000
xs = [float(i) for i in range(n)]
a = np.arange(n, dtype=np.float64)
def best_time(f, reps):
"""Mejor tiempo de varias repeticiones, en segundos por llamada (el reloj del navegador es grueso)."""
best = float("inf")
for _ in range(5):
t0 = time.perf_counter()
for _ in range(reps):
f()
best = min(best, (time.perf_counter() - t0) / reps)
return best
t_py = best_time(lambda: sum(x * x for x in xs), reps=1)
t_np = best_time(lambda: float(np.dot(a, a)), reps=200)
print(f"Python puro: {1e9 * t_py / n:6.1f} ns por elemento")
print(f"NumPy: {1e9 * t_np / n:6.2f} ns por elemento")
print(f"cociente: {t_py / t_np:,.0f} veces")In the browser, the difference is around 50 to 60 times (on a desktop machine with CPython we measured between 20 and 50, depending on load: both sides run faster). Tidier Python does not fix this: it is the fixed cost of interpreting each operation separately. With more work per element the ratio falls, but does not disappear: with four arithmetic operations instead of one, each operation adds ten to twenty nanoseconds to Python and one to four to NumPy, because each operation creates and traverses an entire temporary array. In the browser the ratio remains in the tens; on a desktop, where those temporaries no longer fit in cache, it falls to about five times, and avoiding temporaries recovers the rest. The solution is moving the loop into compiled code that processes whole arrays: vectorization. The next lessons open that box: how NumPy stores data in memory (the ndarray memory model), how to write computations as array operations (vectorization), and later where interpreter overhead comes from and when writing a C++ extension pays off.
Common mistakes
Exercises
For the first two, the snippet is:
g = (x * x for x in range(4))
print(sum(g), sum(g))
g = (x * x for x in range(4)), you run total = sum(g) and then m = max(g). What happens?for epoch in range(10): for batch in loader: .... It works with a DataLoader, but with loader = (b for b in batches) it only trains for the first epoch. What is the precise explanation?def add(x, acc=[]): acc.append(x); return acc, what does the third call return in the sequence add(1), add(2), add(3, [])?fib(n) = n if n < 2 else fib(n - 1) + fib(n - 2) and without caching, how many calls to fib in total (including the initial one) does fib(25) make?'naïve λ ≤ 1€' occupy in UTF-8? (It has 12 code points, including three spaces.)first(xs: Sequence[T]) -> T returns xs[0], find(names: list[str], key: str) -> int | None returns the index or None, load_names() -> list[str] may return an empty list, cfg: dict[str, float] and Scheduler is a Protocol with def step(self) -> None. Which lines does mypy flag as errors?More than one answer may be correct.
def mean(xs: list[float]) -> float and ints: list[int] = [1, 2, 3]. mypy rejects mean(ints), even though every int is accepted where a float is expected. Why is that decision correct?timed, which records the duration in seconds of every call in the global dictionary TIMINGS, under the key label if given, otherwise under the function name, in a list (TIMINGS[clave], created if absent). It must work as @timed, @timed() and @timed(label='paso'); preserve name and documentation with functools.wraps; return the function's result; and record duration even if the function raises an exception, which must propagate.import functools, time
TIMINGS = {}
def timed(fn=None, *, label=None):
# @timed llega aquí con fn = la función; @timed(...) llega con fn = None
passOPTIONS stores options such as precision or deterministic. Implement two versions of a context manager that temporarily changes an option: the class OverrideOption(name, value), with __enter__ and __exit__, and the function override_option(name, value) with contextlib.contextmanager. Both must set OPTIONS[name] = value on entry; provide the previous value via as (or None if the option did not exist); on exit, restore the previous value or remove the option if absent, even if the body raises an exception, which must propagate; and work when nested.import contextlib
OPTIONS = {"precision": "float32", "deterministic": False}
class OverrideOption:
def __init__(self, name, value):
self.name, self.value = name, value
def __enter__(self):
pass
def __exit__(self, exc_type, exc, tb):
pass
@contextlib.contextmanager
def override_option(name, value):
yieldOptimConfig must raise ValueError if lr is not positive, and ModelConfig if dropout is not in . Then implement override(cfg, assignment), which receives an assignment such as 'optim.lr=1e-3' or 'seed=3' and returns a modified copy (the original does not change), converting the text to the field's annotated type (int, float, bool or str). For bool, accept true/false/1/0 case-insensitively (watch out: bool('false') is True). A nonexistent field must raise KeyError, and an invalid value the validation's ValueError.import typing
from dataclasses import dataclass, field, fields, replace
@dataclass(frozen=True)
class OptimConfig:
lr: float = 3e-4
weight_decay: float = 0.0
@dataclass(frozen=True)
class ModelConfig:
d_model: int = 256
dropout: float = 0.1
bias: bool = True
@dataclass(frozen=True)
class Config:
seed: int = 0
name: str = "baseline"
model: ModelConfig = field(default_factory=ModelConfig)
optim: OptimConfig = field(default_factory=OptimConfig)
def override(cfg, assignment):
# 'optim.lr=1e-3' -> copia de cfg con cfg.optim.lr == 0.001
return cfgSummary
- Data model.
for,with,obj(x),obj.a,len,[]and operators call special methods looked up on the type. An iterable creates iterators; an iterator is exhausted.__exit__always executes, with the exception as an argument. - Generators. A lazy pipeline uses bounded memory regardless of ; one eager stage makes it grow with and breaks interleaving. A generator consumed twice is empty without an error.
- Text.
strcontains code points andbytescontains bytes; normalize (NFC) before comparing, compile regular expressions as raw strings, and count withCounter. - Decorators.
@disf = d(f). Always usefunctools.wraps;lru_cachetrades memory for time and requires hashable arguments. - Types. Python ignores annotations;
mypyandpyrightcheck them without executing, across all branches. Generics,X | Nonewith narrowing,LiteralandProtocolcover almost all numerical code. Mutable containers are invariant. - Dataclasses.
frozen=True,slots=True,default_factoryand validation in__post_init__; modify them withreplace. Freezing is shallow: use immutable fields. - Shapes. jaxtyping with beartype checks named axes at runtime on every call; test with different sizes per axis to reveal mix-ups.
- Performance. The interpreter costs tens of nanoseconds per operation; the solution is to vectorize.