Sub topic 14
When to use TypedDict, dataclasses or a validation library
This chapter assumes you have read the earlier chapters on TypedDict and Literal. You should know that a type checker such as mypy or pyright reads annotations separately from the running program. You should also be comfortable with classes and the dataclasses module. By the end you will be able to pick the right tool for a piece of data and say why.
Ask where the data comes from
Choosing a tool depends less on syntax than on one question: who produced this data, and can you trust its shape?
- Data your own code builds is already shaped correctly. A type checker is enough to catch your mistakes.
- Data from outside your process, such as JSON from an API, a config file or user input, can have any shape. Only code that runs at runtime can check it.
TypedDict and dataclass only help the type checker. A validation library is the one tool of the three that rejects bad data while the program runs. The rest of the chapter follows from that difference.
Comparing the three
| Property | TypedDict | dataclass | Validation library (for example pydantic) |
|---|---|---|---|
| Runtime type of an instance | `dict` | A new class | A new class (or a checked `dict`) |
| Checks values at runtime | No | No | Yes |
| Access syntax | `item["key"]` | `item.key` | `item.key` |
| Methods and defaults | No methods, optional keys only | Yes, with `field` defaults | Yes |
| Serializes to JSON directly | Yes | Needs `asdict` first | Built-in helpers |
| Extra cost | None | Small object creation | Parsing work on every input |
| Needs a third-party package | No | No | Yes |
TypedDict: describe dictionaries that already exist
Use TypedDict when the data must remain a dictionary. Typical cases are:
- JSON that you pass through
json.loadsandjson.dumps. - Keyword arguments, as in the
Unpackchapter. - Existing code that already indexes with
["key"]and that you want to type without rewriting.
Nothing is converted, so there is no overhead. The cost is that the annotation is only a promise. json.loads returns Any, so annotating its result as a TypedDict tells the checker to believe you.
You can make that promise honest with a small validating function. A TypeGuard return type tells the checker that when the function returns True, the value has the stated type.
import json
from typing import Literal, TypedDict, TypeGuard
class Event(TypedDict):
kind: Literal["click", "key"]
timestamp: float
def is_event(value: object) -> TypeGuard[Event]:
return (
isinstance(value, dict)
and value.get("kind") in ("click", "key")
and isinstance(value.get("timestamp"), (int, float))
)
raw = json.loads('{"kind": "click", "timestamp": 12.5}')
if is_event(raw):
print(raw["kind"], raw["timestamp"])
else:
print("rejected")This works for small shapes. Writing these functions by hand for nested data quickly becomes tedious and error-prone, because nothing forces the guard to match the class. If you add a key to Event and forget the guard, the checker will not warn you.
Dataclasses: your own objects with behavior
Use a dataclass when you control the data and want a real object. You get attribute access, default values, __repr__ and __eq__ for free. You can also add methods, make instances immutable with frozen=True, and use replace to create modified copies.
from dataclasses import dataclass, field, replace
from typing import Literal
Status = Literal["open", "closed"]
@dataclass(frozen=True)
class Ticket:
id: int
status: Status = "open"
tags: list[str] = field(default_factory=list)
def close(self) -> "Ticket":
return replace(self, status="closed")
ticket = Ticket(1)
print(ticket.close())
print(Ticket(2, "bogus")) # flagged by a type checker, runs without errorThe second print shows that a dataclass does not validate. Literal and the int annotation are again only information for the checker. If you want a runtime check inside a dataclass, you must write it yourself in __post_init__.
Converting a dataclass to a dictionary requires dataclasses.asdict. Converting a dictionary into a dataclass requires Ticket(**data). That call fails on unexpected keys and does not check values, so it is not a safe way to ingest untrusted data.
Validation libraries: untrusted input
A validation library such as pydantic checks data when it enters your program. It reports every problem it finds, and it can convert values to the declared types. In the example below, install it with pip install pydantic.
from typing import Literal
from pydantic import BaseModel, ValidationError
class Ticket(BaseModel):
id: int
status: Literal["open", "closed"] = "open"
print(Ticket.model_validate({"id": "7"}))
try:
Ticket.model_validate({"id": "7", "status": "bogus"})
except ValidationError as exc:
print(exc.error_count(), "problem found")The first call succeeds. The string "7" is converted to the integer 7 and status takes its default. The second call fails because "bogus" is not one of the Literal values. Your Literal annotation is now enforced, which it never was in the earlier chapters.
Two points matter when you adopt a library:
- Conversion is a behavior you must choose deliberately. By default pydantic accepts
"7"for anint. Strict modes exist if you want to reject it. - Validation costs time on every input. For data that crosses a trust boundary this is the right cost. For a tight loop over data you built yourself it is wasted work.
Pydantic can also validate a TypedDict directly through TypeAdapter, so you can keep dictionaries as your data format and still check them at the boundary.
Combining the tools
The tools do not exclude each other. A common layered design looks like this:
- At the boundary, validate untrusted input with a library or a
TypeGuardfunction. - Inside the program, pass the result around as a
TypedDictif it must stay a dictionary, or as a dataclass if you want behavior. - At the output boundary, convert back to a dictionary for JSON.
Tagged unions of TypedDict fit well with step 2. A message queue that carries {"kind": "circle", ...} and {"kind": "rectangle", ...} dictionaries can be handled with the narrowing and assert_never pattern from the earlier chapter, with no conversion step.
Edge cases and failure modes
- A checked type that is not true. If you annotate
json.loadsoutput as aTypedDictwithout validation, a missing key still raisesKeyErrorat runtime, and the checker reports nothing. The type checker is only as reliable as the boundary code. - Dictionaries have no behavior. If you find yourself writing free functions that always take the same
TypedDictfirst, consider a dataclass so that those functions become methods. - Extra keys. A
TypedDictargument accepts a dictionary with extra keys when the dictionary comes from a variable, because of structural compatibility. A literal with an unknown key is flagged. A hand-writtenTypeGuarddoes not reject extra keys unless you add that check. - Equality. Two dataclass instances with equal fields are equal. A
TypedDictinstance is a plain dictionary, so it compares like one, and a dataclass never equals a dictionary with the same contents. - Dependencies. Adding a validation library adds a package to maintain. For a short script that reads one config file, a
TypeGuardfunction may cost less than the dependency.
A short rule of thumb
- Plain dictionary needed, data trusted:
TypedDict. - Object with behavior, data trusted:
dataclass. - Data from outside, shape uncertain: a validation library, or a hand-written guard for very small cases.
- Both an untrusted source and a dictionary format: validate at the edge, then use
TypedDictinside.
Exercise
A service receives JSON from a mobile app, reads fields such as user_id and plan (one of "free" or "pro"), and then passes the data to several internal functions. Which tool do you use at the boundary, and why can a TypedDict or a dataclass alone not do that job?
Show answer
Use a validation library (or a hand-written guard) at the boundary. The JSON comes from outside the program, so its shape is not guaranteed. TypedDict and dataclass annotations, including Literal["free", "pro"], are only read by the type checker and are not enforced at runtime, so a request with plan "gold" would pass through unnoticed. After validation, the internal functions can use a TypedDict or a dataclass.
Exercise
What does this code print, and what would a type checker report? from dataclasses import dataclass from typing import Literal @dataclass class Light: color: Literal["red", "green"] print(Light("blue"))
Show answer
It prints Light(color='blue'). The dataclass does no runtime validation, so the program runs without error. A type checker reports that "blue" is not assignable to Literal["red", "green"].