compare approaches one problem · two ways
Compare Approaches
The same problem solved different ways in Python, run on the same input, with what really differs and when to use each.
TypedDict vs dataclassbehaves differently
Describe an API record and see what you get at runtime.
what differs
A TypedDict is a plain dict at runtime: type(p) is dict and you index with strings. A dataclass creates instances of a new class. Neither validates types when the program runs; both are for type checkers.
at a glance
| approach | use it when |
|---|---|
| A · TypedDict | Annotating dicts that stay dicts (JSON in, JSON out) so a type checker can help. |
| B · dataclass | A real object with attribute access, methods, defaults and equality. |
Watch out: Use NotRequired[...] in a TypedDict for optional keys; use __post_init__ in a dataclass to validate.
the outputs
Each approach runs on the same input.
concepts
typing.TypedDictstatic typing
learn it
related comparisons
Hand-written class vs @dataclass · Nested dicts vs dataclass models