Type hints and dataclasses
Add type hints and dataclasses so editors catch shape mistakes early.
Why it matters: ML configs and eval rows are typed records. Wrong types (a string "0.2" as a float) cause silent bugs.
Basics
Annotating functions
Type hints are optional. Python does not check them at runtime.
They help editors, autocomplete, and tools like mypy.
Modern syntax: list[str], dict[str, float], str | None.
Common mistake: annotating every local variable. Annotate public function signatures instead.
Tiny example
Add types to parameters and the return value.
def score(text: str) -> int:
return len(text)
print(score("prompt"))Basics
Dataclasses
@dataclass builds __init__, __repr__, and __eq__ from annotated fields.
frozen=True makes the object immutable. Good for configs.
For mutable defaults use field(default_factory=list), not = [].
Tiny example
Build a small frozen config and print a field.
from dataclasses import dataclass
@dataclass(frozen=True)
class Cfg:
model: str
lr: float = 2e-5
print(Cfg("mini").lr)Basics
Validation note
Dataclasses do not validate values. They only store them.
In production, libraries like pydantic parse and check fields at the API boundary.
In this sandbox we keep checks simple with float(...) and assert.
Tiny example
Check a value at a boundary with a plain assert.
req = {"temperature": "0.2"}
temp = float(req["temperature"])
assert 0.0 <= temp <= 2.0
print("ok", temp)Then AI / ML
AI / ML examples
Same idea, used in real AI work. Press Try in lab to run it.
AI / ML example
AI / ML: typed train config
A frozen dataclass holds model settings safely.
In AI / ML: Training scripts pass typed configs into fit loops and eval jobs.
example.py
Python
from dataclasses import dataclass
@dataclass(frozen=True)
class TrainConfig:
model_name: str
epochs: int = 3
learning_rate: float = 2e-5
cfg = TrainConfig(model_name="bert-base")
print(cfg.model_name, cfg.learning_rate)AI / ML example 2
AI / ML: retrieved chunk record
One dataclass per hit keeps scores and tags together.
In AI / ML: RAG pipelines sort Chunk objects by score before building context.
example.py
Python
from dataclasses import dataclass, field
@dataclass
class Chunk:
doc_id: str
text: str
score: float = 0.0
tags: list[str] = field(default_factory=list)
hits = [Chunk("d1", "Python ML", 0.91, ["python"]), Chunk("d2", "K8s", 0.55)]
hits.sort(key=lambda c: c.score, reverse=True)
print(hits[0].doc_id, hits[0].score)Takeaways
- 1Type hints document intent; tools check them, runtime does not.
- 2Dataclasses turn dict bags into clear internal objects.
- 3Validate at boundaries; keep configs frozen when possible.