Sub topic 10
Typing structured data with TypedDict and dataclasses
This chapter assumes you can annotate functions and variables and run mypy or Pyright, as covered in earlier chapters. It shows two ways to describe records with a fixed set of named fields.
Why `dict[str, object]` is not enough
JSON payloads and config files often arrive as dictionaries with known keys. If you annotate such a value as dict[str, object], the checker knows nothing about individual keys. Every lookup returns object, so you must narrow it before use.
A TypedDict fixes this. It declares the exact keys and the type of each value.
TypedDict
from typing import TypedDict
class Movie(TypedDict):
title: str
year: int
ok: Movie = {"title": "Alien", "year": 1979}
bad: Movie = {"title": "Alien"} # flagged: required key "year" is missingThe checker now catches several mistakes:
- A missing required key, as in
badabove. - An extra key that the class does not declare.
- A wrong value type, such as
"year": "1979". - A lookup of an unknown key, such as
ok["director"].
Reading ok["year"] gives int, so ok["year"] + 1 type-checks.
By default every key is required. To make all keys optional, write class Movie(TypedDict, total=False). Reading an optional key with [] can still fail at runtime, so use .get() and handle None.
Dataclasses
A dataclass describes a real class. Its fields come from annotations, and the @dataclass decorator generates __init__, __repr__, and __eq__.
from dataclasses import dataclass, field
@dataclass(frozen=True)
class Review:
author: str
stars: int
tags: list[str] = field(default_factory=list)
review = Review(author="Ada", stars=5)
print(review.stars + 1)
review.stars = 4 # flagged: frozen dataclass attribute is read-only
Review("Ada", "five") # flagged: str is not intThe checker reads the annotations to type the generated __init__. It reports wrong argument types, missing arguments, and assignment to frozen fields. Use field(default_factory=list) for mutable defaults. A plain = [] is an error in the standard library, and checkers flag it too.
Choosing between them
| Need | TypedDict | dataclass |
|---|---|---|
| Data already is a `dict` (JSON, kwargs) | Yes | Needs conversion |
| Attribute access (`obj.title`) | No, use `obj["title"]` | Yes |
| Methods and defaults | No | Yes |
| Immutability | No | `frozen=True` |
| Runtime type | Plain `dict` | Its own class |
Use a TypedDict at the boundary where dictionaries enter your program. Convert to a dataclass for the code that works with the data.
from dataclasses import dataclass
from typing import TypedDict
class MovieDict(TypedDict):
title: str
year: int
@dataclass
class Movie:
title: str
year: int
@classmethod
def from_dict(cls, data: MovieDict) -> "Movie":
return cls(title=data["title"], year=data["year"])
movie = Movie.from_dict({"title": "Alien", "year": 1979})
print(movie)Exercise
A function receives {"name": "Ada"} where the type is class User(TypedDict): name: str; age: int. What does the checker report, and does the program fail at runtime?
Show answer
The checker reports that the required key "age" is missing. At runtime the dictionary is still a normal dict, so nothing fails until code reads user["age"] and raises a KeyError.