Sub topic 2
Describing a dictionary's shape with TypedDict
This chapter assumes you know basic Python dictionaries, functions and classes, and simple type hints such as int and list[str]. It also assumes you know that a static checker such as mypy or pyright reads annotations separately from running the code.
The problem with `dict[str, Any]`
Dictionaries often carry records: a movie, a user, a JSON response. The annotation dict[str, Any] says nothing about which keys exist or what their values are. A checker accepts movie["tittle"] and movie["year"].upper() without complaint, and you find the bug at runtime.
A TypedDict fixes this. It declares the exact string keys of a dictionary and the type of each value.
Defining a TypedDict
Use the class syntax. Each annotated line is one key.
from typing import TypedDict
class Movie(TypedDict):
title: str
year: int
def describe(movie: Movie) -> str:
return f"{movie['title']} ({movie['year']})"
movie: Movie = {"title": "Blade Runner", "year": 1982}
print(describe(movie))The output is Blade Runner (1982).
The class body only lists annotations. You cannot add methods or default values. The class is a description for the checker, not a new kind of object.
What the checker catches
With Movie in place, a checker reports each of these mistakes before the code runs:
| Code | Problem reported |
|---|---|
| `movie["tittle"]` | `tittle` is not a key of `Movie` |
| `movie["year"].upper()` | `int` has no method `upper` |
| `{"title": "Alien"}` assigned to `Movie` | the required key `year` is missing |
| `{"title": "Alien", "year": 1979, "rating": 5}` | `rating` is an extra key |
By default every key is required, and extra keys are rejected. The next chapters show how to make keys optional.
Creating instances
There are two ways to build a value.
from typing import TypedDict
class Point(TypedDict):
x: int
y: int
a: Point = {"x": 1, "y": 2}
b = Point(x=3, y=4)
print(a, b)
print(type(b))Both produce an ordinary dict. The second form looks like a constructor, but Point(...) returns a plain dictionary, so type(b) prints <class 'dict'>. You cannot use isinstance(b, Point), because TypedDict classes do not support that check.
Common errors
- Using dot access.
movie.titlefails. A TypedDict is still a dictionary, so writemovie["title"]. - Expecting defaults. Writing
year: int = 0in the class body is an error. Supply every required key when you build the value. - Assuming the data is validated. If you parse JSON and annotate the result as
Movie, the checker trusts you. A missing key still raisesKeyErrorat runtime. - Mixing up a dict and a class. Do not use
isinstanceor call methods on the type. Use a dataclass if you need behavior.
Returning a TypedDict
Functions can also build and return the type. The checker then verifies the dictionary you return.
from typing import TypedDict
class Movie(TypedDict):
title: str
year: int
def make_movie(title: str, year: int) -> Movie:
return {"title": title, "year": year}
print(make_movie("Alien", 1979))If you left out "year", the checker would flag the return statement.
Exercise
You annotate data: Movie = json.loads(text) and the JSON lacks a year key. Does the checker report an error, and what happens when you later read data["year"]?
Show answer
The checker reports nothing, because json.loads returns Any and the annotation is trusted. Reading data["year"] raises KeyError at runtime, since a TypedDict is a plain dict and performs no validation.