runtime

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

approachuse it when
A · TypedDictAnnotating dicts that stay dicts (JSON in, JSON out) so a type checker can help.
B · dataclassA 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

TypedDict and Protocol

related comparisons

Hand-written class vs @dataclass · Nested dicts vs dataclass models

A · TypedDict
B · dataclass
Compare Python Approaches · Runtime