Sub topic 14
When to use TypedDict, dataclasses or a validation library
This chapter assumes you can read TypedDict and Literal annotations and know that a type checker such as mypy or pyright runs separately from your program. You have seen that a TypedDict is an ordinary dict at runtime. Here you will use that fact to pick the right tool.
The deciding question
Ask two questions about your data:
- Where does it come from? Data you create yourself is trusted. Data from JSON, a request body, a file or a user is untrusted.
- What do you do with it? You might pass it along as a dictionary, or you might attach behavior to it.
Comparing the three
| Tool | Runtime type) checks | Instance is a | Best for |
|---|---|---|---|
| `TypedDict` | None | `dict` | Typing dict-shaped data you already have |
| `dataclass` | None | Your own class | Internal objects with attributes and methods |
| Validation library (for example pydantic) | Yes | Model class | Data from outside your program |
TypedDict: the data is already a dictionary
Use TypedDict when dictionaries are already part of the design. Examples are parsed JSON, **kwargs options and return values from a library. It adds no conversion step and no new class to learn. Instances serialize with json.dumps as they are.
A dataclass needs a conversion step before it can be written back out. The TypedDict does not.
import json
from dataclasses import dataclass
from typing import TypedDict
class MovieDict(TypedDict):
title: str
year: int
@dataclass
class Movie:
title: str
year: int
raw = json.loads('{"title": "Blade Runner", "year": 1982}')
as_dict: MovieDict = raw
movie = Movie(**raw)
print(as_dict["title"], movie.year)
print(json.dumps(as_dict))Both MovieDict and Movie describe the same data. The dictionary version round-trips through JSON unchanged. The dataclass gives you attribute access (movie.year), a readable repr, default values and methods.
Dataclass: you want an object
Choose a dataclass when the data is created inside your program and needs behavior. It has real attributes, supports frozen=True for immutability, and can define methods. A dataclass does not check types when you build it. Movie(title=1, year="x") runs without error.
Validation library: you cannot trust the input
A type checker only sees your source code. It cannot know that a request body contains "year": "nineteen". A validation library checks values when the program runs, and it can convert them.
from pydantic import BaseModel, ValidationError
class Movie(BaseModel):
title: str
year: int
try:
Movie.model_validate({"title": "Blade Runner", "year": "nineteen"})
except ValidationError as error:
print(error.error_count(), "problem found")Install it with pip install pydantic. The example prints 1 problem found.
Literal fields are checked in the same way. A field typed Literal["r", "w"] rejects any other value when the data is loaded.
Combining them
These tools are not exclusive. A common pattern is to validate at the boundary and use plain types inside. Some validation libraries can also validate against an existing TypedDict. Pydantic's TypeAdapter is one example. On Python versions before 3.12, pydantic requires TypedDict imported from typing_extensions for this.
Common mistakes
- Using a
TypedDictfor untrusted input and assuming it was validated. - Using a dataclass only to get type hints on a dictionary you must keep as a dictionary.
- Adding a validation library to code that only passes trusted values between your own functions.
Exercise
Your service receives a JSON body from a web client and passes the result to internal functions that only read fields. Which tool do you use at the entry point, and which do you use for the internal functions' parameter types? Give a reason for each.
Show answer
Use a validation library at the entry point, because the body is untrusted and a type checker cannot verify it at runtime. After validation, the internal functions can take a TypedDict (if the data stays a dict) or a dataclass (if you need attributes and methods), because the data is now trusted and runtime checks would only repeat work.