Sub topic 10
Typing structured data with TypedDict and dataclasses
This chapter assumes you can run mypy or Pyright on a project and read their error messages. It also assumes you know str | None unions and narrowing. You need Python 3.11 or newer for the NotRequired example. On 3.10, import NotRequired from typing_extensions instead.
Real programs pass around records: a movie with a title and a year, a user with a name and an email. Python gives you two common ways to model them. A dictionary with fixed keys can be typed with TypedDict. A class that mostly holds fields can be written as a dataclass. Both give the checker enough detail to find wrong keys, wrong value types, and wrong constructor calls.
Why dict[str, object] is not enough
An annotation such as dict[str, object] says nothing about which keys exist or what each value is. dict[str, Any] is worse, because it turns checking off for every value you read. For a record with a known shape, neither one helps you find bugs.
TypedDict: a dict with a fixed shape
A TypedDict declares the exact keys of a dictionary and the type of each value.
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 reports these mistakes:
- A missing required key, as on the last line above.
- A key that is not declared, such as
{"title": "Alien", "year": 1979, "genre": "horror"}. - A value of the wrong type, such as
"year": "1979". - A read of an undeclared key, such as
ok["director"].
Reading a declared key gives the declared type. ok["year"] is an int, and you can use it without narrowing.
What happens at runtime
A TypedDict class is only a description for the checker. At runtime the object is an ordinary dict. Nothing validates the keys or the values, and isinstance(x, Movie) raises a TypeError. If the data comes from outside your program, such as JSON, the checker cannot protect you. The section on boundary data below covers that case.
Optional keys
By default every key is required. Mark a key that may be absent with NotRequired.
from typing import NotRequired, TypedDict
class Movie(TypedDict):
title: str
year: int
director: NotRequired[str]
def describe(movie: Movie) -> str:
if "director" in movie:
return f"{movie['title']} by {movie['director']}"
return movie["title"]The in check narrows the key. Inside the if, both mypy and Pyright accept movie["director"]. Without the check, they flag the read as possibly missing. You can also write class Movie(TypedDict, total=False) to make every key optional. Then use Required[...] on the keys that must stay required.
Note that NotRequired[str] means the key may be absent. It does not mean the value may be None. If the value can be None, write str | None. A key can be both absent-able and None-able.
The get method
movie.get("director") is allowed for any declared key. For a NotRequired[str] key, its type is str | None, so you must narrow it before calling string methods.
Compatibility with plain dicts
A TypedDict is not a dict[str, object], because a function holding the wider type could insert keys or values that break the record's shape. It is compatible with the read-only Mapping[str, object]. If a function only reads, annotate its parameter with Mapping. If you pass a plain dict[str, str] where a Movie is expected, the checker rejects it, because it cannot know which keys exist.
Dataclasses: typed classes with generated methods
The @dataclass decorator generates __init__, __repr__, and __eq__ from the annotated class attributes. Both checkers understand this and check calls against the generated __init__.
from dataclasses import dataclass, field
@dataclass
class Order:
order_id: int
customer: str
items: list[str] = field(default_factory=list)
note: str | None = None
order = Order(1, "Ada")
order.items.append("book")
Order(1) # flagged: missing argument "customer"
Order("1", "Ada") # flagged: str is not intDefaults and field order
A field with a default cannot come before a field without one. Python raises a TypeError when the class is defined, and the checkers report it first. A mutable default such as items: list[str] = [] raises a ValueError, so use field(default_factory=list). To make fields keyword-only, use @dataclass(kw_only=True), available from Python 3.10. Then the order rule no longer applies.
Frozen dataclasses
@dataclass(frozen=True) makes instances immutable. Assigning to a field is a runtime error, and the checkers flag it before that.
from dataclasses import dataclass
@dataclass(frozen=True)
class Point:
x: float
y: float
p = Point(1.0, 2.0)
p.x = 3.0 # flagged: Point is frozen, attribute is read-onlyFrozen instances are also hashable, so you can use them as dictionary keys or set members.
Annotations are not enforced
A dataclass does not check types when it builds an instance. Order("1", "Ada") fails only under the checker. At runtime it creates an object whose order_id is a string. As with TypedDict, the guarantee holds only for code the checker has seen.
Choosing between them
| Question | TypedDict | dataclass |
|---|---|---|
| Runtime object | Plain `dict` | Instance of a class |
| Access syntax | `record["title"]` | `record.title` |
| Can have methods | No | Yes |
| Fits JSON and existing dict APIs | Directly | Needs conversion |
| Defaults | Optional keys only | Field defaults and factories |
| Immutability | Not available as a class option | `frozen=True` |
Checking data at the boundary
json.loads returns Any. If you annotate the result as a Movie, the checker accepts it without question, and a bad payload fails later in unrelated code. The safer approach is to validate once where data enters the program, using narrowing, and build a typed object.
import json
from dataclasses import dataclass
@dataclass
class Movie:
title: str
year: int
def load_movie(text: str) -> Movie:
raw = json.loads(text)
if not isinstance(raw, dict):
raise ValueError("expected a JSON object")
title = raw.get("title")
year = raw.get("year")
if not isinstance(title, str):
raise ValueError("title must be a string")
if not isinstance(year, int) or isinstance(year, bool):
raise ValueError("year must be an integer")
return Movie(title, year)
print(load_movie('{"title": "Alien", "year": 1979}'))After the checks, title is a str and year is an int, so Movie(title, year) type-checks for a real reason. The extra isinstance(year, bool) test is needed because bool is a subclass of int, and True would otherwise pass as a year.
Common errors
- Treating
TypedDictas a runtime check. It never validates anything, andisinstancedoes not work with it. - Using
total=Falsewhen only one key is optional. PreferNotRequiredon that key. - Passing a
TypedDictto a function that takesdict[str, object]. UseMapping[str, object]for read-only access. - Writing
x: list[str] = []as a dataclass field. Usedefault_factory. - Annotating
json.loads(...)output directly instead of narrowing it. - Expecting a dataclass to convert
"1979"to1979. It stores whatever you pass in.
Exercise
You receive a JSON object with the keys "name" (str) and "age" (int), and "email" (str) may be absent. Write a TypedDict for it. Then explain why annotating the result of json.loads with that TypedDict does not make the data safe.
Show answer
Use class User(TypedDict): name: str; age: int; email: NotRequired[str], written with one field per line. The annotation only tells the checker what to assume. json.loads returns Any, so the checker accepts the assignment without inspecting the data, and the TypedDict is a plain dict at runtime with no validation. A payload with a missing "name" or a string "age" would pass the checker and fail later. To make the data safe, check it with isinstance and key tests (or a runtime validation library) before treating it as a User.