Sub topic 14
Describing dictionary shapes with TypedDict
This chapter assumes you can read basic annotations such as dict[str, int] and str | None. It also assumes you have run mypy or pyright on a file. Examples use Python 3.11 or later, because NotRequired was added to typing in 3.11. On older versions, import it from typing_extensions.
The problem with dict[str, object]
Many programs pass around dictionaries that have a fixed set of keys, such as a parsed JSON record or a configuration block. The annotation dict[str, object] says little about such a value. A checker cannot tell which keys exist or what type each value has. dict[str, str | int] is no better. Every lookup returns the full union, so you must narrow it each time.
TypedDict gives each key its own type.
from typing import TypedDict
class Movie(TypedDict):
title: str
year: int
def describe(movie: Movie) -> str:
return f"{movie['title']} ({movie['year']})"
print(describe({"title": "Alien", "year": 1979}))Inside describe, a checker knows that movie["title"] is a str and movie["year"] is an int. A key that is not declared, such as movie["rating"], is reported as an error.
What the checker reports
A checker validates dictionary literals against the declared shape.
from typing import TypedDict
class Movie(TypedDict):
title: str
year: int
missing: Movie = {"title": "Alien"} # error: missing key "year"
extra: Movie = {"title": "Alien", "year": 1979, "stars": 5} # error: extra key "stars"
wrong: Movie = {"title": "Alien", "year": "1979"} # error: "year" must be intThe exact wording differs between mypy and pyright. The three problems are reported by both: a missing key, an extra key, and a wrong value type. The same checks apply when you assign to a key, as in movie["year"] = "x".
It is still a plain dict at runtime
TypedDict follows the rule from earlier in this tutorial: hints are not enforced at runtime. A Movie is an ordinary dict. Creating one performs no validation, and the class cannot be used with isinstance.
from typing import TypedDict
class Movie(TypedDict):
title: str
year: int
movie: Movie = {"title": "Alien", "year": "not a number"} # runs fine
print(type(movie))
print(Movie.__annotations__)
try:
isinstance(movie, Movie)
except TypeError as error:
print("TypeError:", error)The first print shows <class 'dict'>. The isinstance call raises TypeError, because a TypedDict class cannot be used for instance checks. If you need to verify data at runtime, check it yourself or use a validation library.
A small hand-written validator turns that belief into a checked fact.
import json
from typing import TypedDict
class Movie(TypedDict):
title: str
year: int
def parse_movie(text: str) -> Movie:
data = json.loads(text)
if not isinstance(data, dict):
raise ValueError("expected a JSON object")
title = data.get("title")
year = data.get("year")
if not isinstance(title, str) or not isinstance(year, int):
raise ValueError("title must be str and year must be int")
return {"title": title, "year": year}
print(parse_movie('{"title": "Alien", "year": 1979}'))Optional keys
By default every key is required. There are two ways to mark a key as optional.
NotRequired[...]marks a single key. This is the clearer choice.total=Falsemakes every key in the class optional.Required[...]can then mark individual keys as required again.
from typing import NotRequired, TypedDict
class Movie(TypedDict):
title: str
year: int
rating: NotRequired[float]
plain: Movie = {"title": "Alien", "year": 1979}
rated: Movie = {"title": "Alien", "year": 1979, "rating": 8.5}
if "rating" in rated:
print(rated["rating"] + 1)
print(plain.get("rating", 0.0))Reading an optional key with movie["rating"] is an error unless the checker can see that the key is present. The in test above narrows it. The alternative is .get(), which returns float | None when you give no default.
An optional key differs from a key whose value may be None. rating: NotRequired[float] allows the key to be absent. rating: float | None requires the key but allows the value None. Choose the one that matches your data.
Inheritance and keys that are not identifiers
A TypedDict can extend another one. The child has all the parent's keys plus its own.
from typing import TypedDict
class Movie(TypedDict):
title: str
year: int
class Show(Movie):
seasons: int
show: Show = {"title": "Dark", "year": 2017, "seasons": 3}
print(show)Some real keys are not valid Python names, such as "Content-Type". For these, use the functional form, which takes the key names as strings.
from typing import TypedDict
Headers = TypedDict("Headers", {"Content-Type": str, "X-Request-Id": str})
headers: Headers = {"Content-Type": "text/plain", "X-Request-Id": "abc123"}
print(headers["Content-Type"])Compatibility rules and gotchas
- A
TypedDictis not a subtype ofdict[str, object]. A function that acceptsdict[str, object]may add arbitrary keys, which would break the shape, so checkers reject the call. AcceptMapping[str, object]when you only need to read. - Keys are always
strliterals. A checker cannot verifymovie[name]whennameis an ordinarystrvariable. Pyright and mypy both report this or treat the result loosely. - Structural matching applies. A dict literal needs no declared relationship to
Movie. Only its keys and value types matter. del movie["title"]on a required key is an error.- Methods such as
updateandsetdefaultare checked against the declared shape.
Choosing between a dict, a TypedDict, and a dataclass
| Need | TypedDict | dataclass |
|---|---|---|
| Value is a real `dict` | Yes | No |
| Works directly with `json.dumps` | Yes | Needs `asdict` |
| Methods and defaults | No | Yes |
| Runtime validation | No | No |
| Attribute access (`movie.title`) | No | Yes |
Use TypedDict where the data already arrives or leaves as a dictionary. Use a dataclass when you build the object yourself and want methods, defaults, or attribute access.
Exercise
Given class Movie(TypedDict): title: str; year: int; rating: NotRequired[float], which of these does a checker accept without narrowing: movie["rating"], movie.get("rating"), or movie["title"]? What does the checker infer for movie.get("rating")?
Show answer
It accepts movie["title"] and movie.get("rating"). It rejects movie["rating"], because the key may be absent. The result of movie.get("rating") is float | None, so you must check for None before doing arithmetic on it.
Exercise
This code passes the type checker. What happens when you run it, and why does the checker not catch the problem? import json from typing import TypedDict class Movie(TypedDict): title: str year: int movie: Movie = json.loads('{"title": "Alien"}') print(movie["year"])
Show answer
It raises KeyError: 'year'. json.loads returns Any, and a value of type Any is accepted for any annotation. The checker therefore trusts the Movie annotation. TypedDict does no runtime validation, so the missing key is found only when the line runs. Validate the parsed data before returning it as a Movie.