Sub topic 1
Why dict[str, Any] is not enough
Dictionaries carry a lot of data in Python programs: parsed JSON, configuration, API responses, database rows. The usual annotation for them is dict[str, Any]. It tells a type checker almost nothing, so many mistakes go unreported until the code runs. This chapter shows where that happens and introduces the two tools the rest of the tutorial covers, TypedDict and Literal.
Prerequisites
This chapter assumes you know:
- Basic Python syntax, including dictionaries, functions and classes.
- Simple type hints such as
int,str,list[str]andOptional. - That a static type checker such as mypy or pyright reads annotations separately from running the code.
What dict[str, Any] promises
The annotation dict[str, Any] says two things: the keys are strings, and each value can be anything. Any is a special type that switches checking off for a value. The checker accepts every operation on it.
The checker therefore cannot know which keys exist or what type each value has. Here is a function that reads a movie record:
from typing import Any
def describe(movie: dict[str, Any]) -> str:
return f"{movie['titel']} ({movie['year']})"
movie = {"title": "Blade Runner", "year": 1982}
print(describe(movie))The key 'titel' is a typo. mypy and pyright accept this code, because any string is a valid key for dict[str, Any]. The program fails at runtime with KeyError: 'titel'.
Three problems it hides
- Misspelled keys. The checker cannot tell
'titel'from'title'. - Wrong value types.
movie["year"] + 1is accepted even ifyearholds the string"1982". - Missing documentation. A reader must find where the dictionary is built to learn its keys. Editor autocompletion cannot suggest them either.
A related problem concerns values that must come from a small fixed set. Suppose a function accepts a file mode. With a plain str annotation, the checker accepts "rw", "read" and "" as readily as "r".
The two tools in this tutorial
TypedDict lets you declare the exact keys of a dictionary and the type of each value. The same function can then be checked properly:
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))If you write movie['titel'] here, the checker reports that 'titel' is not a key of Movie. You find the bug before running anything.
Literal limits a value to specific constants, such as Literal["r", "w", "a"]. Combined with TypedDict, it lets you model records that come in several shapes. The later chapters cover that.
What changes and what does not
Both versions of describe behave identically when the program runs. The annotations add no checks of their own. A TypedDict instance is still an ordinary dict, and Python does not verify its contents. The benefit comes from running a type checker, ideally in your editor and in continuous integration. The chapter on runtime behavior covers this in more detail.
When dict[str, Any] is still fine
Use dict[str, Any] when the keys really are open-ended, such as a free-form metadata bag or a cache keyed by arbitrary strings. Use TypedDict when your code expects a fixed set of known keys.
Exercise
A function takes config: dict[str, Any] and reads config["port"]. A caller passes a dictionary that has only the key "prot". Does a type checker report this? What would you change so that it does?
Show answer
No. For dict[str, Any] the checker accepts any string key, so the failure appears as a KeyError at runtime. Define a TypedDict with a port: int key and annotate the parameter with it. The checker then flags the missing port key at the call site.