Sub topic 1
Why dict[str, Any] is not enough
Python programs pass dictionaries around constantly. They hold parsed JSON, rows from a database, configuration, and API responses. The usual annotation for them is dict[str, Any]. This chapter shows what that annotation lets through, why that matters, and which two tools in the typing module address it: TypedDict and Literal. The rest of the tutorial covers those tools in detail. Here you learn the problem they solve and the limits that apply to them.
Prerequisites
This chapter assumes you have:
- Basic Python syntax, including dictionaries, functions and classes.
- Familiarity with simple type hints such as
int,str,list[str]andOptional. - Awareness that a static type checker such as mypy or pyright reads your annotations separately from running the code.
The examples use Python 3.9 or newer. Later chapters note where a feature needs 3.11 or 3.13. To follow along with checking, install mypy or pyright and run it on a file, for example mypy example.py.
Where loosely typed dictionaries come from
Dictionaries are the natural result of most data-loading code:
json.loadsreturns dictionaries, lists and primitives.- A web framework hands you a request body as a dictionary.
- A YAML or TOML loader gives you nested dictionaries.
- Many database drivers can return each row as a dictionary.
All of these produce a record: a dictionary with a fixed, known set of string keys, where each key has its own value type. A movie record has a title that is a string and a year that is an integer. The built-in dict type cannot express that. Its annotation has one slot for all keys and one slot for all values.
What dict[str, Any] tells a checker
Any is the type that turns checking off. A value of type Any is accepted wherever any type is expected, and any operation on it is allowed. With dict[str, Any], the checker knows only that the keys are strings. It knows nothing about which keys exist or what the values are.
from typing import Any
def describe(movie: dict[str, Any]) -> str:
return f"{movie['title']} ({movie['yaer']})"
movie = {"title": "Blade Runner", "year": 1982}
print(describe(movie))The key 'yaer' is a typo. A checker run on this file reports no error, because any string is a valid key for dict[str, Any]. Running it fails with KeyError: 'yaer'. The mistake is found only when that line executes, and in a rarely used code path that may be in production.
Wrong value types slip through in the same way:
from typing import Any
def next_year(movie: dict[str, Any]) -> int:
return movie["year"] + 1
print(next_year({"title": "Alien", "year": "1979"}))The year was stored as a string. The checker sees Any + 1, which is always allowed. At runtime Python raises TypeError: can only concatenate str (not "int") to str.
Static checking versus running the code
A static checker reads source code and your annotations without executing anything. Python itself ignores annotations when it runs the program. Both facts matter for everything that follows.
With dict[str, Any] the left path has nothing to report, so every error falls to the right path.
Why not just use a more precise dict type
A natural reaction is to replace Any with a union of the value types:
def next_year(movie: dict[str, int | str]) -> int:
return movie["year"] + 1The checker now rejects this, because movie["year"] could be a str, and str + int is invalid. The checker is not being picky. The annotation really does say any value might be a string. To satisfy it you would add an isinstance check at every access, even though you know year is always an integer.
The root problem is that dict[K, V] describes a collection: any number of keys, all of one key type and one value type. A record is a different thing. It has specific keys, each with its own type. No choice of K and V captures that.
What goes wrong, summarized
| Problem | With `dict[str, Any]` | With a record type |
|---|---|---|
| Misspelled key | Not detected; fails at runtime | Reported by the checker |
| Wrong value type | Not detected | Reported by the checker |
| Missing key when building a dict | Not detected | Reported by the checker |
| Extra, unexpected key | Not detected | Reported by the checker |
| Editor autocomplete on keys | None | Keys are suggested |
| Result of `movie["year"]` | `Any` | `int` |
The last row has an easy-to-miss consequence. Since values are Any, the damage spreads. A variable assigned from movie["year"] is also Any, so errors you make with it later go unreported too.
A first look at the fix
TypedDict declares the keys of a dictionary and the type of each value. Here is the movie record, written once:
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))This prints Blade Runner (1982). A checker now knows movie['year'] is an int. If you write movie['yaer'], it reports that Movie has no such key. If you build {"title": "Alien"} and annotate it as Movie, it reports the missing year. The next chapter covers the syntax in full.
Some fields hold values from a small fixed set, such as a status or a mode. A plain str annotation is too loose there as well. Literal restricts a value to specific constants:
from typing import Literal
Mode = Literal["r", "w", "a"]
def open_log(path: str, mode: Mode) -> None:
print(f"opening {path} with mode {mode}")
open_log("app.log", "r") # accepted
open_log("app.log", "x") # rejected by a type checker, still runs normallyThe second call runs and prints a line. The checker, though, reports that "x" is not one of "r", "w" or "a". A typo such as "rw" is caught the same way.
The two tools work together. A Literal field inside a TypedDict can tell a checker which of several record shapes it is looking at. That technique, called a tagged union, appears later in the tutorial.
Limits to know from the start
Three more points prevent common misunderstandings:
- Annotations do not convert data. Declaring
year: intdoes not turn"1979"into1979. It only lets the checker flag code that claims a string is an integer. - A passing check is only as good as the declaration. If you annotate unvalidated JSON as
Movie, the checker trusts you. Wrong data then produces errors far from where it entered. - You do not have to convert everything at once. A function that takes
dict[str, Any]can usually be changed to take aTypedDictone function at a time, and a checker will point out the callers that need fixing.
Common errors at this stage
- Treating
Anyas "any of the types I mean".Anymeans "do not check", while a union likeint | strmeans "one of these". They behave very differently, as thenext_yearexample showed. - Expecting the interpreter to enforce annotations. Running
python example.pynever reports a type error from annotations. Run a checker separately, ideally in your editor and in continuous integration. - Using
dict[str, object]as a saferAny. It is stricter, but it still has no per-key information, so every access needs narrowing. - Assuming a
TypedDictis a new kind of object. It is a way to describe adict, as the runtime chapter will show.
Exercises
Exercise
A function takes movie: dict[str, Any] and reads movie["tilte"]. Why does a type checker accept it, and when is the mistake found?
Show answer
With dict[str, Any] any string is a valid key and every value is Any, so the checker has nothing to compare against. The mistake appears only when the line runs, as a KeyError.
Exercise
Why does changing the annotation to dict[str, int | str] not solve the problem of knowing that year is an integer?
Show answer
dict[K, V] has one value type for all keys. The annotation says every value might be a str or an int, so the checker rejects movie["year"] + 1 unless you narrow the value first. A record needs a type that assigns a type to each key, which is what TypedDict does.
Exercise
You annotate the result of json.loads(text) as Movie, a TypedDict. The JSON actually contains {"title": "Alien", "year": "1979"}. Does Python or the checker report an error, and why?
Show answer
Neither. The checker trusts the annotation, and at runtime a TypedDict is a plain dict with no validation. The wrong type surfaces later, when code treats year as an integer. Data from outside the program needs a separate validation step.