Sub topic 2
Describing a dictionary's shape with TypedDict
Prerequisites
This chapter assumes you can write Python functions, classes, and dictionaries. It also assumes you know simple hints such as int, str, list[str], and Optional. Finally, it assumes you know that a static type checker such as mypy or pyright reads your annotations separately from Python running the code. The examples run on any current Python 3 version.
The problem a TypedDict solves
Dictionaries are the default way to pass structured data around in Python. JSON responses, configuration files, and database rows all become dictionaries. The usual annotation, dict[str, Any], says almost nothing. A checker can't tell you that movie["titel"] is a typo, or that year should hold an integer.
A TypedDict is a type that names the exact string keys a dictionary has and the type of each value. It adds no new runtime behavior, so your data stays a plain dict. It gives the checker enough information to catch mistakes before the program runs.
Defining a TypedDict
You define a TypedDict with 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 class body looks like a dataclass, but only annotations are allowed. You can't give a key a default value, and you can't define methods. The names on the left are the dictionary keys, written as strings when you use them.
The checker now knows what describe expects. It also knows that movie["title"] is a str and movie["year"] is an int, so those values support the operations of those types without any extra casts.
What the checker reports
By default, every key you declare is required. The dictionary must contain exactly the declared keys, no more and no fewer. The following mistakes are all reported by a checker, and none of them stops the program from running.
from typing import TypedDict
class Movie(TypedDict):
title: str
year: int
a: Movie = {"title": "Alien"} # missing key "year"
b: Movie = {"title": "Alien", "year": "1979"} # wrong value type
c: Movie = {"title": "Alien", "year": 1979, "genre": "x"} # extra key "genre"
d: Movie = {"title": "Alien", "year": 1979}
print(d["titel"]) # unknown key
d["year"] = "1979" # wrong type on assignment
del d["year"] # deleting a required keyRun as written, this program fails only on the d["titel"] line, with a KeyError. The checker, however, reports every line marked in the comments. The table summarizes what to expect.
| Mistake | Checker's view |
|---|---|
| Missing required key in a literal | Error: key is required |
| Extra key in a literal | Error: key is not defined |
| Wrong value type | Error: incompatible type |
| Reading an undeclared key | Error: not a defined key |
| Deleting a required key | Error: key is required |
The exact wording differs between mypy and pyright, but the categories are the same.
Three ways to build a value
You can create a Movie in several ways, and all of them produce a normal dictionary.
from typing import TypedDict
class Point(TypedDict):
x: int
y: int
def origin() -> Point:
return {"x": 0, "y": 0}
p1: Point = {"x": 1, "y": 2} # dict literal with a declared type
p2 = Point(x=3, y=4) # call syntax with keyword arguments
p3 = origin() # returned from an annotated function
print(p1, p2, p3)The literal form works because the checker uses the declared type as context. Without the annotation, {"x": 1, "y": 2} would be inferred as dict[str, int]. That type is not a Point, and passing it to a function that expects a Point is reported as an error. Writing the annotation, or passing the literal directly as an argument, supplies the context.
Nested and composite shapes
A key's type can be another TypedDict, a list of them, or any other type. This is how you describe a JSON-like document.
from typing import TypedDict
class Address(TypedDict):
street: str
city: str
class Customer(TypedDict):
name: str
address: Address
tags: list[str]
def city_of(customer: Customer) -> str:
return customer["address"]["city"]
customer: Customer = {
"name": "Ada",
"address": {"street": "1 Main St", "city": "Leeds"},
"tags": ["vip"],
}
print(city_of(customer))The checker follows the chain. customer["address"] is an Address, and ["city"] on it is a str. A typo at any level is reported.
The diagram shows where each part of the process happens.
Common errors
Using isinstance with a TypedDict. A TypedDict is not a real class you can test against, so this raises an error.
from typing import TypedDict
class Movie(TypedDict):
title: str
year: int
movie: Movie = {"title": "Alien", "year": 1979}
try:
isinstance(movie, Movie)
except TypeError as error:
print(error)
print(isinstance(movie, dict))Test against dict instead. If you need to check the contents, write the checks by hand or use a validation library.
Using attribute access. movie.title raises AttributeError, because the value is a dictionary. Use movie["title"].
Expecting validation. Annotating a value does not check it. Data from json.loads has the type Any, so the checker accepts it as a Movie without looking inside. Declaring the type is a promise you make, and the checker trusts it. To keep the promise, check the data at the boundary where it enters your program.
import json
from typing import TypedDict
class Movie(TypedDict):
title: str
year: int
def parse_movie(raw: object) -> Movie:
if not isinstance(raw, dict):
raise TypeError("expected a JSON object")
title = raw.get("title")
year = raw.get("year")
if not isinstance(title, str) or not isinstance(year, int):
raise ValueError("invalid movie")
return {"title": title, "year": year}
movie = parse_movie(json.loads('{"title": "Alien", "year": 1979}'))
print(movie["title"])After this function returns, the rest of the code can rely on the declared shape. The checks in parse_movie are ordinary Python, and the TypedDict only describes the result.
Passing a loosely typed dictionary. A value of type dict[str, str] is not accepted where a Movie is expected, even if it happens to contain the right keys. The checker can't know which keys exist. Build the value with a literal or with Movie(...) so the checker can verify it.
Giving keys defaults. Writing year: int = 0 in the class body is an error. For keys that may be missing, use the optional-key tools covered in a later chapter.
Misspelling keys in other code. The checker only protects code it can see typed. If a function takes dict[str, Any], a Movie can be passed in, but nothing inside that function is checked. Annotate parameters with the TypedDict itself to keep the protection.
Reading the declared shape at runtime
The class still carries information you can inspect, even though instances are plain dictionaries.
from typing import TypedDict, get_type_hints
class Movie(TypedDict):
title: str
year: int
print(get_type_hints(Movie))
print(sorted(Movie.__required_keys__))This prints the key-to-type mapping and the set of required keys. Tools such as documentation generators and validation libraries use this metadata. A later chapter covers runtime behavior in more detail.
When this fits
Use a TypedDict when your data is already a dictionary, such as parsed JSON, a configuration mapping, or a record handed to you by a library, and you want the checker to understand its shape. You get no runtime cost and no conversion step. If you need methods, defaults, or runtime checks, other tools fit better, and the last chapter compares them.
Exercise
A function is annotated def show(m: Movie) -> None, where Movie is a TypedDict with required keys title: str and year: int. A caller passes {"title": "Alien", "year": "1979"}. Does the program raise an error when it runs, and does a type checker report anything?
Show answer
The program does not raise an error at the call, because TypedDict values are not validated at runtime, and show runs normally unless its body fails on the string. A type checker reports the call, because the value for year is a str where an int is declared.
Exercise
Write a TypedDict named Book with a title (string), a pages (integer), and an authors key holding a list of strings. Then write a function first_author(book: Book) -> str that returns the first author.
Show answer
from typing import TypedDict class Book(TypedDict): title: str pages: int authors: list[str] def first_author(book: Book) -> str: return book["authors"][0]
Exercise
Why does isinstance(movie, Movie) raise a TypeError, and what should you write instead to check at runtime that a value is a dictionary?
Show answer
A TypedDict class exists only to describe a shape for the type checker, so Python does not allow instance checks against it. Use isinstance(value, dict), then check the individual keys and value types yourself or with a validation library.