Skip to content

12. Type hints

A data pipeline reads text from files and APIs, turns it into numbers and records, and passes them through many functions. A wrong type in one place, such as a price that is still a string, often shows up much later as a crash or, worse, as a wrong number. Type hints write down what each function expects and returns. A type checker such as mypy reads them and finds these bugs before you run the code. This module teaches the hints you need for data work: collections, missing values, functions as arguments, JSON records, generic helpers and “anything with fit and predict”.

  • Annotate variables, parameters and return values with built-in types and generics such as list[float] and dict[str, list[int]], and mark missing values with X | None.
  • Describe functions as values with Callable, fixed sets of options with Literal and JSON records such as data/customers.json with TypedDict.
  • Write generic functions, generic classes and type aliases with the modern syntax (def first[T], class Box[T], type), and read the older TypeVar form.
  • Use Protocol for structural typing, and cast and @overload where the checker needs help.
  • Run mypy in normal and strict mode, read its report and fix what it finds. Know pyright as an alternative.
  • Explain why hints check nothing at runtime, and validate untrusted data at the boundary.

mypy is in the course requirements (python/requirements.txt). Check it with mypy --version in your activated environment.

Python is dynamically typed: a variable has no fixed type, and Python checks types only when a line runs. This makes code short and flexible. It also means that a type mistake stays hidden until the exact line with the mistake runs, maybe after 40 minutes of data loading, maybe only for the one customer record without a phone number.

A type hint (also called a type annotation) is a note in the code that says which type a variable, parameter or return value should have. def mean_reading(readings: list[float]) -> float: says “give me a list of floats, and I give back a float”.

Hints help in four ways:

Who reads the hints What you get
a person documentation that cannot drift as easily as a comment, right in the signature
your editor autocompletion of methods and keys, and red underlines for mistakes as you type
a static type checker (mypy, pyright) a report of type bugs in the whole project, before the code runs
some libraries at runtime validation and parsing: dataclasses, pydantic, FastAPI and Typer read hints to build behavior

Static means “by reading the code, without running it”. Runtime is the moment the code actually runs. A static type checker is a program that reads your source code and the hints, works out the type of every expression and reports the places where the types do not fit.

flowchart LR
    C["Code with hints<br/>clean.py"] --> M["mypy clean.py<br/>(static: reads the code)"]
    C --> P["python clean.py<br/>(runtime: runs the code)"]
    M --> R["Report:<br/>line 27: error ..."]
    P --> O["Output or a crash"]

Hints are optional. You can add them to one function at a time, and the checker checks the parts that have them. This approach is called gradual typing. Most real projects grow their hints this way.

Annotate variables, parameters and return values

Section titled “Annotate variables, parameters and return values”

The syntax has three forms:

  • A parameter: name: type, with a default after it: discount: float = 0.0.
  • A return value: -> type after the parameter list. A function that returns nothing has -> None.
  • A variable: name: type = value. You rarely need it, because the checker infers (works out) the type from the value. Use it when the value alone is not clear, such as an empty list: values: list[float] = [].
def line_revenue(quantity: int, unit_price: float, discount: float = 0.0) -> float:
"""Return the revenue of one order line, rounded to cents."""
return round(quantity * unit_price * (1 - discount), 2)
units_sold: int = 3
print(line_revenue(units_sold, 249.0, 0.1))
for name, hint in line_revenue.__annotations__.items():
print(f"{name}: {hint}")
Output
672.3
quantity: <class 'int'>
unit_price: <class 'float'>
discount: <class 'float'>
return: <class 'float'>

Python stores the hints of a function in its __annotations__ dict. It does not use them. A hint is any expression that names a type: a class such as int, or a more detailed form such as list[float].

Two small rules make hints easier to write:

  • An int is accepted where a float is expected. line_revenue(3, 249, 0.1) passes the check, because every whole number is also a number. This rule is called numeric promotion.
  • bool is a subtype of int: a True is accepted where an int is expected. A subtype is a type whose values are also valid values of another type.

This is the most important fact of the module. Python reads the hints and stores them, and then ignores them. A wrong type passes straight through:

def top_three(values: list[int]) -> list[int]:
"""Return the three largest values, largest first."""
return sorted(values, reverse=True)[:3]
quantities = ["2", "25", "1", "10", "3"] # read from a CSV file: still text
print(top_three(quantities))
count: int = "3"
print(count, type(count).__name__)
Output
['3', '25', '2']
3 str

No error. The function sorted the strings in text order, where "3" comes after "25", and returned a wrong answer: the largest quantity is 25, not 3. The variable count holds a str although its hint says int. A silent bug like this one, a wrong result with no error, is the most expensive kind in data work, because it ends up in a report.

To find the bug, you need a separate tool that reads the code: a type checker.

mypy is the original Python type checker. It is a command-line program. You give it files or folders, and it prints one line per problem. Here is the same bug in a script that reads the real data/sales.csv:

top_units.py
"""Find the three largest order quantities in data/sales.csv."""
def top_three(values: list[int]) -> list[int]:
"""Return the three largest values, largest first."""
return sorted(values, reverse=True)[:3]
with open("data/sales.csv", encoding="utf-8") as f:
next(f) # skip the header row
quantities = [line.split(",")[10] for line in f] # column 10 is quantity
print(top_three(quantities))
Output
['6', '6', '6']

The real top quantities are 25, 25 and 25. Python ran the script and printed nonsense. Now ask mypy:

Terminal
mypy top_units.py
Output
top_units.py:13: error: Argument 1 to "top_three" has incompatible type "list[str]"; expected
"list[int]" [arg-type]
print(top_three(quantities))
^~~~~~~~~~
Found 1 error in 1 file (checked 1 source file)

mypy did not run the script. It read it. It knows that line.split(",") returns a list[str], so quantities is a list[str], and top_three wants a list[int]. Read a mypy line from left to right:

Part Meaning
top_units.py:13: the file and the line number
error: the severity: error or note (extra information)
Argument 1 to "top_three" has incompatible type ... the message: what the checker found and what it expected
[arg-type] the error code: a short name for the kind of error, used to look it up or to silence one line
Found 1 error in 1 file the summary; with no errors: Success: no issues found in 1 source file

The two indented lines show the source line, with ^~~~ under the exact expression. They appear because this course’s examples run mypy with pretty = true in pyproject.toml. Put this file in your project folder to get the same output:

pyproject.toml
[tool.mypy]
python_version = "3.12"
pretty = true

python_version = "3.12" makes mypy check the code against Python 3.12, the oldest version this course supports. pretty = true shows the source line and wraps long messages to the width of your terminal, so your line breaks can differ from the ones on this page.

The fix is one conversion: [int(line.split(",")[10]) for line in f].

By default, mypy is gentle. It skips the inside of functions that have no hints at all, so you can add hints to an old project one function at a time. Strict mode (mypy --strict) turns on a group of extra checks. The most important ones:

Strict check It reports
disallow-untyped-defs a function with missing hints (Function is missing a type annotation)
disallow-untyped-calls a call from typed code to a function without hints
warn-return-any a function that returns a value of unknown type (Any) although it promises a type
warn-unused-ignores a # type: ignore comment that is no longer needed

Use strict mode for new code. You can switch it on for the whole project in pyproject.toml with strict = true.

reveal_type(expr) asks the checker for the type it infers for an expression. mypy prints it as a note. Import it with from typing import reveal_type. At runtime, reveal_type() prints the runtime type to stderr and returns its argument unchanged, so you can leave it in while you investigate. Remove it afterwards.

When mypy is wrong, or a library has no hints, silence one line with a comment that names the error code: x = legacy_call() # type: ignore[no-untyped-call]. Always name the code. A bare # type: ignore hides every future error on that line too.

pyright is a type checker from Microsoft. It powers the Pylance extension in VS Code, so you may already see its underlines in your editor. Like mypy, it follows the Python typing specification and bundles typeshed, the collection of standard-library hints. The course uses mypy. To try pyright from the terminal:

Terminal
uv pip install pyright # or: pip install pyright
pyright top_units.py

Newer checkers written in Rust, such as ty from the makers of ruff, are in development. They target the same typing specification.

Built-in generics and abstract collections

Section titled “Built-in generics and abstract collections”

A generic type is a type that takes other types as parameters, written in square brackets. list[float] is “a list whose items are floats”. The types in the brackets are type arguments. Since Python 3.9, the built-in collections accept them directly:

Hint Means Data example
list[float] a list of floats, any length temperatures of one sensor
dict[str, float] keys are str, values are float revenue per region
dict[str, list[int]] keys are str, values are lists of int quantities per store
set[str] a set of strings the categories seen in a file
tuple[str, float] exactly 2 items: a str, then a float ("S1", 21.7)
tuple[float, ...] any number of floats; the ... means “and so on” all readings of one sensor, stored immutably
units_by_store: dict[str, list[int]] = {"S01": [1, 2, 1], "S02": [3, 1]}
price_range: tuple[float, float] = (5.99, 1299.0)
categories: set[str] = {"Books", "Home"}
totals: dict[str, int] = {store: sum(units) for store, units in units_by_store.items()}
print(totals)
print(sorted(categories), price_range[1] - price_range[0])
Output
{'S01': 4, 'S02': 4}
['Books', 'Home'] 1293.01

The module collections.abc holds abstract collection types. They describe what a value can do, not which class it is:

Hint Accepts Promises you can
Iterable[float] a list, tuple, set, generator, file of lines, … loop over it once
Iterator[str] a generator or other iterator call next() on it, loop once
Sequence[float] a list, tuple, range, str index it, slice it, take len(), loop many times
Mapping[str, float] a dict and other read-only mappings look up keys; no promise that you can change it

A good rule for parameters and return values: accept the most general type that works, return a specific type. A function that only loops over its input should accept Iterable[float], so callers can pass a list, a tuple or a generator. It should return a list[float], so callers know exactly what they get.

There is a second reason to prefer Sequence for inputs. list is invariant: a list[int] is not accepted where a list[float] is expected, because the function could append a float to the caller’s list of ints. Sequence is read-only, so a Sequence[int] is accepted where a Sequence[float] is expected. This is called covariance: Sequence is covariant, because it follows the rule “an int is accepted as a float” for its items.

X | None means “an X or None”. The | builds a union type: a value of one of several types, such as int | str. A union with None is often called an optional type. Use it for every value that can be missing: a reading that failed to parse, a customer without a phone number, the result of a search that found nothing.

Before you use the value, you must rule out None. The checker follows your if statements. After if code is None: return 0.0, it knows that code is a str in the rest of the function. This is called type narrowing: a check makes the type of a variable more precise inside one branch.

def discount_rate(code: str | None) -> float:
"""Return the discount for a promo code; no code means no discount."""
if code is None:
return 0.0
return 0.2 if code.upper() == "BLACKFRIDAY" else 0.05
print(discount_rate(None), discount_rate("blackfriday"), discount_rate("spring"))
Output
0.0 0.2 0.05

Without the if, mypy reports Item "None" of "str | None" has no attribute "upper" [union-attr]. These checks narrow a type: x is None, x is not None, isinstance(x, str), if x: (it removes None, and also empty values), "key" in record for some dicts, and an early return or raise.

Older code writes Optional[str] and Union[int, str], imported from typing. They mean exactly str | None and int | str. Write the | form in new code.

Any (from typing) is the type of “I don’t know, so don’t check”. A value of type Any can do anything and goes anywhere. json.load() returns Any, because nothing tells Python what the file contains. Every value that comes from Any is unchecked, so bugs hide there. Strict mode warns when Any leaks out of a function that promises a real type.

object is the opposite. Every value is an object, so a parameter value: object accepts anything. But the checker allows only what every object can do (print it, compare it with ==). You must narrow it with isinstance() before you use it. Use object for “anything, and I will check it”. Use Any only as a last resort.

A function is a value: you pass it to sorted(key=...), register it in a dict or wrap it in a decorator. Callable[[ArgType1, ArgType2], ReturnType] from collections.abc describes a function by its parameter types and return type.

from collections.abc import Callable
def convert_all(values: list[float], convert: Callable[[float], float]) -> list[float]:
"""Apply a unit conversion to every reading and round to 1 decimal."""
return [round(convert(value), 1) for value in values]
def celsius_to_fahrenheit(celsius: float) -> float:
return celsius * 9 / 5 + 32
print(convert_all([21.0, 21.9, 21.4], celsius_to_fahrenheit))
print(convert_all([21.0, 21.9, 21.4], lambda c: c + 273.15))
Output
[69.8, 71.4, 70.5]
[294.1, 295.0, 294.5]

Callable[[float], float] is “a function that takes one float and returns a float”. The checker accepts the named function and the lambda, and it would reject a function that takes two parameters or returns a str. Callable[..., float] accepts any parameters. Use it only when the parameters really vary.

Literal["mean", "median"] (from typing) is a type whose only values are the listed constants. It is the right hint for a parameter that accepts a few fixed strings, like the strategy of scikit-learn’s SimpleImputer or the how of a pandas merge. A typo such as "meen" becomes a checker error instead of a runtime error deep inside the library.

from statistics import mean, median
from typing import Literal
def fill_missing(
values: list[float | None], strategy: Literal["mean", "median"] = "mean"
) -> list[float]:
"""Replace None with the mean or the median of the known values."""
known = [v for v in values if v is not None]
fill = mean(known) if strategy == "mean" else median(known)
return [fill if v is None else v for v in values]
print(fill_missing([21.0, None, 21.4, 25.0]))
print(fill_missing([21.0, None, 21.4, 25.0], strategy="median"))
Output
[21.0, 22.466666666666665, 21.4, 25.0]
[21.0, 21.4, 21.4, 25.0]

Literal values can be strings, bytes, integers, booleans, None and enum members.

Records from JSON files and APIs are dicts with fixed keys, such as {"average": 3.8, "count": 216}. dict[str, float] cannot say that count is an int while average is a float. A TypedDict describes a dict with known keys, each with its own type. You write it with class syntax: one line per key.

from typing import NotRequired, TypedDict
class Rating(TypedDict):
average: float
count: int
class Product(TypedDict):
id: str
name: str
rating: Rating
stock: NotRequired[int] # some records leave this key out
earbuds: Product = {
"id": "P001",
"name": "Wireless Earbuds",
"rating": {"average": 3.8, "count": 216},
}
print(earbuds["rating"]["count"], type(earbuds).__name__)
print(sorted(Product.__required_keys__), sorted(Product.__optional_keys__))
Output
216 dict
['id', 'name', 'rating'] ['stock']

The keys of a TypedDict are required by default. NotRequired[int] marks a key that may be missing. (The reverse, total=False on the class plus Required[...] on single keys, also exists.) At runtime, a TypedDict value is a plain dict: type(earbuds) is dict. The class exists for the checker, which then catches misspelled keys, missing keys and values of the wrong type.

Use a TypedDict for data that already is a dict, such as parsed JSON. For records you create yourself, a dataclass (module 21) is usually better: it has attribute access, defaults and methods.

A type alias is a short name for a long type. Python 3.12 added the type statement for it:

type Row = list[float]
type Matrix = list[Row]
type Plan = Literal["basic", "standard", "premium"]
def column_means(X: Matrix) -> Row:
"""Return the mean of every column of a row-major matrix."""
return [sum(column) / len(column) for column in zip(*X, strict=True)]
houses: Matrix = [[2420.0, 4.0], [1610.0, 2.0], [1260.0, 2.0]] # sqft, bedrooms
print(column_means(houses))
print(Matrix.__value__)
Output
[1763.3333333333333, 2.6666666666666665]
list[Row]

The alias makes the signature read like the problem: a function from a matrix to a row. Matrix.__value__ shows what the alias stands for. The type statement evaluates its value only when someone asks, so an alias can refer to names that are defined later. Older code writes a plain assignment, Matrix = list[list[float]], or Matrix: TypeAlias = list[list[float]].

An alias is the same type as its value: a list[list[float]] is a Matrix. When you want a distinct type, use NewType from typing: CustomerId = NewType("CustomerId", str). The checker then rejects a plain str where a CustomerId is expected, so an order id cannot be passed by mistake. At runtime, CustomerId("C00001") is just the string.

Some functions do not care about the item type. first(items) returns the first item of a list of floats, a tuple of customer ids or a list of records. A hint such as Sequence[Any] -> Any throws the type information away. A type parameter keeps it: def first[T](items: Sequence[T]) -> T says “whatever type the items have, the result has the same type”. T is a type variable: a placeholder that the checker fills in at each call. A function or class with type parameters is generic.

from collections.abc import Sequence
def first[T](items: Sequence[T]) -> T:
"""Return the first item of a sequence."""
return items[0]
print(first([21.0, 21.9, 21.4]), first(("C00001", "C00002")))
Output
21.0 C00001

For first([21.0, 21.9, 21.4]), the checker sets T to float, so the result is a float. For the tuple of ids, T is str.

A type parameter can have a bound: def largest[T: float](values: Sequence[T]) -> T accepts only types that are float or a subtype (such as int), so you can compare and add the values inside. Several type parameters are allowed: def invert[K, V](mapping: dict[K, V]) -> dict[V, K].

A class in one paragraph. A class defines a new kind of object. class Box: starts the definition. Functions inside it are its methods. The special method __init__ runs when you create an object with Box(...), and self is the object itself, so self.item = item stores a value on it. Module 18 teaches classes in full; here you need only this much.

A generic class takes type parameters in brackets after its name:

class Box[T]:
"""Hold one value of any type and give it back with its type."""
def __init__(self, item: T) -> None:
self.item = item
def get(self) -> T:
return self.item
price_box = Box(79.99) # the checker infers Box[float]
id_box = Box[str]("P001") # or state the type argument yourself
print(price_box.get() * 2, id_box.get().lower())
Output
159.98 p001

The bracket syntax after the name (first[T], Box[T]) arrived in Python 3.12 (PEP 695). Most code and tutorials written before 2024 use the older form. It creates the type variable as a separate object and makes a class generic by inheriting from Generic[T]:

from collections.abc import Sequence
from typing import Generic, TypeVar
T = TypeVar("T") # the old way: a module-level type variable
def first_old(items: Sequence[T]) -> T:
return items[0]
class OldBox(Generic[T]):
def __init__(self, item: T) -> None:
self.item = item
print(first_old([21.0, 21.9]), OldBox("P001").item)
Output
21.0 P001

Both forms describe the same generic functions and classes. One difference: the new syntax infers variance (whether a Box[int] counts as a Box[float]) from how the class uses T; an old TypeVar is invariant unless you declare covariant=True. A bound is written TypeVar("T", bound=float). Read the old form, write the new one. (The block is marked nolint because ruff’s UP rules ask you to rewrite it in the new syntax.)

scikit-learn does not care which class your model is. Any object with fit and predict methods works in its pipelines and cross-validation tools. This is duck typing: “if it walks like a duck and quacks like a duck, it is a duck”. A Protocol writes this rule down for the checker:

from typing import Protocol
class Predictor(Protocol):
def predict(self, X: list[list[float]]) -> list[float]: ...

The ... (Ellipsis) is the whole body: a protocol lists methods and their signatures, nothing more. Any class that has a matching predict method is a Predictor, without inheriting from it or even importing it. This is structural typing: a type matches by its shape (its methods and attributes). The opposite is nominal typing: a type matches only by its name and inheritance, as with isinstance(x, int) or an abstract base class (module 19).

Protocols are how you type plug-in points: “any model”, “any file-like object with .read()”, “any object with .close()”. The standard library uses them too: collections.abc.Iterable matches any object with an __iter__ method.

Sometimes you know more than the checker. json.load() returns Any, but you know the file holds a CustomerExport. cast(Type, value) from typing tells the checker “treat this value as Type”. It does nothing at runtime: it returns the value unchanged, with no check.

>>> from typing import cast
>>> amount = cast(int, "3")
>>> amount
'3'
>>> type(amount)
<class 'str'>

cast is a promise, not a conversion. If the promise is false, the checker trusts a lie. Use it at one clear boundary (the line that loads the JSON) and validate the data there when it comes from outside (see Example 7).

@overload (from typing) describes a function whose return type depends on the argument types. You write one decorated signature per case, each with ... as its body, and then the real function:

fahrenheit.py
"""One function, two call shapes: @overload tells mypy which is which."""
from typing import overload, reveal_type
@overload
def to_fahrenheit(celsius: float) -> float: ...
@overload
def to_fahrenheit(celsius: list[float]) -> list[float]: ...
def to_fahrenheit(celsius: float | list[float]) -> float | list[float]:
if isinstance(celsius, list):
return [round(c * 9 / 5 + 32, 1) for c in celsius]
return round(celsius * 9 / 5 + 32, 1)
reveal_type(to_fahrenheit(21.5))
reveal_type(to_fahrenheit([21.0, 21.9]))
Output
Runtime type is 'float'
Runtime type is 'list'

At runtime, reveal_type() prints the runtime type. The checker shows the static types:

Terminal
mypy --strict fahrenheit.py
Output
fahrenheit.py:16: note: Revealed type is "float"
fahrenheit.py:17: note: Revealed type is "list[float]"
Success: no issues found in 1 source file

Without the overloads, both calls would have the type float | list[float], and every caller would need an isinstance() check. Notes do not count as errors, so the run still succeeds. Use overloads sparingly. They are common in libraries (pandas and NumPy use many) and rare in application code.

Example 1 — Find a None bug in a sensor pipeline before it runs

Section titled “Example 1 — Find a None bug in a sensor pipeline before it runs”

Goal: data/readings.txt has 43 lines of temperatures, three of them broken. A cleaning script parses each line into float | None and summarizes the readings. It crashes deep inside the standard library. Find the bug with mypy and fix it with narrowing.

Step 1 — Run the script and read the crash

Section titled “Step 1 — Run the script and read the crash”
clean_readings.py
"""Clean data/readings.txt and summarize the temperatures (with a bug)."""
from pathlib import Path
from statistics import mean
def parse_reading(text: str) -> float | None:
"""Return the reading in °C, or None for a broken line."""
try:
return float(text)
except ValueError:
return None
def summarize(values: list[float]) -> dict[str, float]:
"""Return the count, mean, minimum and maximum of the readings."""
return {
"count": len(values),
"mean": round(mean(values), 2),
"min": min(values),
"max": max(values),
}
lines = Path("data/readings.txt").read_text(encoding="utf-8").splitlines()
parsed = [parse_reading(line) for line in lines]
print(summarize(parsed))
Output
TypeError: can't convert type 'NoneType' to numerator/denominator

The last traceback line comes from inside statistics.mean, not from your code. The message talks about numerators, which says nothing about the real cause. You would have to read the whole traceback to find which of your lines passed a None.

Terminal
mypy clean_readings.py
Output
clean_readings.py:27: error: Argument 1 to "summarize" has incompatible type "list[float | None]";
expected "list[float]" [arg-type]
print(summarize(parsed))
^~~~~~
Found 1 error in 1 file (checked 1 source file)

mypy points at line 27 and names the cause. It inferred list[float | None] for parsed from the return hint of parse_reading. summarize promises to work on list[float] only. Note that "count": len(values) is fine in a dict[str, float]: numeric promotion accepts an int as a float.

clean_readings_fixed.py
"""Clean data/readings.txt and summarize the temperatures."""
from pathlib import Path
from statistics import mean
def parse_reading(text: str) -> float | None:
"""Return the reading in °C, or None for a broken line."""
try:
return float(text)
except ValueError:
return None
def summarize(values: list[float]) -> dict[str, float]:
"""Return the count, mean, minimum and maximum of the readings."""
return {
"count": len(values),
"mean": round(mean(values), 2),
"min": min(values),
"max": max(values),
}
lines = Path("data/readings.txt").read_text(encoding="utf-8").splitlines()
parsed = [parse_reading(line) for line in lines]
values = [value for value in parsed if value is not None]
print(summarize(values))
Output
{'count': 40, 'mean': 21.06, 'min': 19.3, 'max': 22.9}

The condition if value is not None inside the comprehension narrows each item, so mypy infers list[float] for values. The three broken lines (error, an empty line and n/a) are gone, and 40 valid readings remain.

Terminal
mypy --strict clean_readings_fixed.py
Output
Success: no issues found in 1 source file

Every function has full hints and no Any leaks out, so strict mode passes too.

Common mistakes:

  • Hinting parse_reading as -> float although it can return None. Then mypy reports the return None line instead (Incompatible return value type), and the real design question, “what happens to broken lines?”, stays hidden. Make the hint tell the truth.
  • Filtering with if value instead of if value is not None. It also drops valid readings of 0.0, which is falsy.
  • Reading only the last traceback line of a crash in a library. The cause is in your code, further up. A checker points straight at it.

Example 2 — Describe customer JSON records with TypedDict

Section titled “Example 2 — Describe customer JSON records with TypedDict”

Goal: data/customers.json holds 20 nested customer records with addresses, tags and orders. Some keys are missing in some records. Describe the records with TypedDicts so that mypy checks every key you read, then report the order spend per plan.

customer_types.py
"""Types for the nested records in data/customers.json."""
import json
from pathlib import Path
from typing import Literal, NotRequired, TypedDict, cast
type Plan = Literal["basic", "standard", "premium"]
class Address(TypedDict):
street: str
city: str
region: str
postal_code: NotRequired[str] # missing for C00005 and C00014
class Order(TypedDict):
order_id: str
date: str
items: int
amount: float
class Customer(TypedDict):
customer_id: str
name: str
email: str
signup_date: str
plan: Plan
address: Address
tags: list[str]
orders: list[Order]
phone: NotRequired[str | None] # absent for most records, null for C00010
class CustomerExport(TypedDict):
exported_at: str
count: int
customers: list[Customer]
def load_export(path: Path) -> CustomerExport:
"""Read the export file. json.load() returns Any, so cast the result."""
with path.open(encoding="utf-8") as f:
return cast(CustomerExport, json.load(f))

The file only defines types and one function, so it prints nothing. Each TypedDict mirrors one level of the JSON. Two kinds of “missing” need two different hints: postal_code is sometimes absent (NotRequired[str]), and phone is absent or present with the JSON value null (NotRequired[str | None]). The Plan alias limits plan to the three real plan names. cast is the one place where the untyped JSON becomes typed data.

customers_report.py
"""Report spend per plan from data/customers.json."""
from pathlib import Path
from customer_types import Customer, Plan, load_export
def total_spend(customer: Customer) -> float:
"""Return the summed order amounts of one customer."""
return round(sum(order["amount"] for order in customer["orders"]), 2)
def spend_by_plan(customers: list[Customer]) -> dict[Plan, float]:
"""Return the total order amount of each plan."""
totals: dict[Plan, float] = {"basic": 0.0, "standard": 0.0, "premium": 0.0}
for customer in customers:
totals[customer["plan"]] += total_spend(customer)
return {plan: round(total, 2) for plan, total in totals.items()}
export = load_export(Path("data/customers.json"))
customers = export["customers"]
print(f"{export['count']} customers, exported at {export['exported_at']}")
first = customers[0]
print(first["name"], first["plan"], total_spend(first))
print(spend_by_plan(customers))
Output
20 customers, exported at 2025-01-02T06:00:00Z
Ana Silva premium 1325.54
{'basic': 5629.3, 'standard': 3895.34, 'premium': 4187.06}
Terminal
mypy --strict customers_report.py
Output
Success: no issues found in 1 source file

mypy also checked customer_types.py, because the report imports it. Inside total_spend, it knows that order["amount"] is a float, so sum() returns a number. In your editor, typing order[" now offers the four keys of an Order.

Step 3 — Let mypy check key names and values

Section titled “Step 3 — Let mypy check key names and values”

This file has three bugs. Python finds the first one only when it runs:

customers_bad.py
"""Three bugs that the Customer TypedDict exposes."""
from pathlib import Path
from customer_types import Customer, load_export
def total_spend(customer: Customer) -> float:
return round(sum(order["ammount"] for order in customer["orders"]), 2)
def upgrade(customer: Customer) -> None:
customer["plan"] = "gold"
def postal_codes(customers: list[Customer]) -> list[str]:
return [customer["address"]["postal_code"] for customer in customers]
customers = load_export(Path("data/customers.json"))["customers"]
print(total_spend(customers[0]))
Output
KeyError: 'ammount'
Terminal
mypy customers_bad.py
Output
customers_bad.py:9: error: TypedDict "Order" has no key "ammount" [typeddict-item]
return round(sum(order["ammount"] for order in customer["orders"]), 2)
^~~~~~~~~
customers_bad.py:9: note: Did you mean "amount"?
customers_bad.py:13: error: Value of "plan" has incompatible type "Literal['gold']"; expected
"Literal['basic', 'standard', 'premium']" [typeddict-item]
customer["plan"] = "gold"
^~~~~~
Found 2 errors in 1 file (checked 1 source file)

mypy finds the typo, with a suggestion, and the invalid plan, without running anything. The upgrade bug would never crash: it would quietly write "gold" into a record, and a later report would miss that customer. mypy does not report the third bug: postal_codes reads the NotRequired key postal_code with [], which raises KeyError for C00005 and C00014. mypy allows this access. pyright’s configuration docs list a rule, reportTypedDictNotRequiredAccess, that flags this access and is on by default. A checker reduces bugs; it does not prove that none are left.

from pathlib import Path
from customer_types import Customer, load_export
def postal_code(customer: Customer) -> str:
"""Return the postal code, or "unknown" when the key is missing."""
return customer["address"].get("postal_code", "unknown")
def phone_status(customer: Customer) -> str:
if "phone" not in customer:
return "absent"
return "null" if customer["phone"] is None else "present"
customers = load_export(Path("data/customers.json"))["customers"]
print([postal_code(c) for c in customers[3:6]])
statuses = [phone_status(c) for c in customers]
print({status: statuses.count(status) for status in ("present", "null", "absent")})
Output
['78449', 'unknown', '48100']
{'present': 6, 'null': 1, 'absent': 13}

.get() with a default never raises, and its result type is str. In phone_status, the check "phone" not in customer narrows the record, so the next line may read customer["phone"], and is None then separates JSON null from a real phone number (a str).

Common mistakes:

  • Writing phone: str | None (required) instead of NotRequired[str | None]. The type then claims that every record has the key, and the checker stops warning about records without it.
  • Using dict[str, Any] for records. It accepts every typo. Spend the five minutes to write the TypedDict.
  • Calling cast in many places. Cast once, in the loader, and let the hints flow from there.

Example 3 — Pick a metric by name with Callable and Literal

Section titled “Example 3 — Pick a metric by name with Callable and Literal”

Goal: A model evaluation script lets the caller choose the metric by name, as scikit-learn’s scoring="r2" does. Type the metric functions, the registry and the name, so that a misspelled name or a metric with the wrong signature fails the check.

Step 1 — Type the metrics and the registry

Section titled “Step 1 — Type the metrics and the registry”
metrics.py
"""Regression metrics that a caller picks by name."""
from collections.abc import Callable, Sequence
from math import sqrt
from typing import Literal
type Metric = Callable[[Sequence[float], Sequence[float]], float]
type MetricName = Literal["mae", "rmse", "r2"]
def mae(y_true: Sequence[float], y_pred: Sequence[float]) -> float:
"""Mean absolute error."""
errors = [abs(t - p) for t, p in zip(y_true, y_pred, strict=True)]
return sum(errors) / len(errors)
def rmse(y_true: Sequence[float], y_pred: Sequence[float]) -> float:
"""Root mean squared error."""
squared = [(t - p) ** 2 for t, p in zip(y_true, y_pred, strict=True)]
return sqrt(sum(squared) / len(squared))
def r2(y_true: Sequence[float], y_pred: Sequence[float]) -> float:
"""Coefficient of determination: 1 minus the share of unexplained variance."""
mean_true = sum(y_true) / len(y_true)
ss_res = sum((t - p) ** 2 for t, p in zip(y_true, y_pred, strict=True))
ss_tot = sum((t - mean_true) ** 2 for t in y_true)
return 1 - ss_res / ss_tot
METRICS: dict[MetricName, Metric] = {"mae": mae, "rmse": rmse, "r2": r2}
def score(
y_true: Sequence[float], y_pred: Sequence[float], metric: MetricName = "mae"
) -> float:
"""Return the chosen metric, rounded to 3 decimals."""
return round(METRICS[metric](y_true, y_pred), 3)
if __name__ == "__main__":
prices = [1097500, 486500, 223000, 431000, 626500] # houses H0001..H0005
predicted = [905000, 512000, 260000, 398000, 701000]
for name in METRICS:
print(name, score(prices, predicted, name))
Output
mae 72500.0
rmse 95618.774
r2 0.893

Two aliases carry the design. Metric says what every metric looks like: two sequences of floats in, one float out. MetricName lists the allowed names. The registry METRICS maps one to the other. The prices are the first five houses of data/houses.csv (lists of int are fine where Sequence[float] is expected), and the predictions are made up for the demo.

Step 2 — Catch a wrong name and a wrong function

Section titled “Step 2 — Catch a wrong name and a wrong function”
metrics_bad.py
"""Two mistakes that the Metric and MetricName hints catch."""
from collections.abc import Sequence
from metrics import METRICS, score
def max_error(errors: Sequence[float]) -> float:
return max(abs(e) for e in errors)
METRICS["max"] = max_error
print(score([3.0, 5.0], [2.5, 5.5], "mse"))
Output
KeyError: 'mse'
Terminal
mypy metrics_bad.py
Output
metrics_bad.py:12: error: Invalid index type "Literal['max']" for
"dict[Literal['mae', 'rmse', 'r2'], Callable[[Sequence[float], Sequence[float]], float]]"; expected
type "Literal['mae', 'rmse', 'r2']" [index]
METRICS["max"] = max_error
^~~~~
metrics_bad.py:12: error: Incompatible types in assignment (expression has type
"Callable[[Sequence[float]], float]", target has type
"Callable[[Sequence[float], Sequence[float]], float]") [assignment]
METRICS["max"] = max_error
^~~~~~~~~
metrics_bad.py:13: error: Argument 3 to "score" has incompatible type "Literal['mse']"; expected
"Literal['mae', 'rmse', 'r2']" [arg-type]
print(score([3.0, 5.0], [2.5, 5.5], "mse"))
^~~~~
Found 3 errors in 1 file (checked 1 source file)

At runtime, the registration “worked” and only the lookup of "mse" crashed. mypy finds three problems: "max" is not a known name, max_error takes one argument instead of two, and "mse" is not a valid name. mypy writes the aliases out in full in its messages, which makes them long. Read the expected type at the end of each message first.

Step 3 — Add a metric that fits the type

Section titled “Step 3 — Add a metric that fits the type”
from collections.abc import Sequence
from metrics import Metric, mae, rmse
def mape(y_true: Sequence[float], y_pred: Sequence[float]) -> float:
"""Mean absolute percentage error, as a fraction."""
ratios = [abs(t - p) / t for t, p in zip(y_true, y_pred, strict=True)]
return sum(ratios) / len(ratios)
chosen: dict[str, Metric] = {"mae": mae, "rmse": rmse, "mape": mape}
prices = [1097500, 486500, 223000, 431000, 626500]
predicted = [905000, 512000, 260000, 398000, 701000]
for name, metric in chosen.items():
print(f"{name:<5} {metric(prices, predicted):>12,.3f}")
Output
mae 72,500.000
rmse 95,618.774
mape 0.118

mape has the same signature as the other metrics, so it is a valid Metric. The registry here uses str keys, because this report builds its own list of metrics. The predictions are off by 11.8% on average.

Common mistakes:

  • Writing Callable[[float, float], float] for a metric that takes two lists. Describe the parameters exactly: Sequence[float].
  • Typing the registry as dict[str, Callable[..., float]]. It accepts any function, so the wrong-signature bug gets through.
  • Validating the metric name with a manual if name not in (...) list that drifts from the registry. With Literal, the type is the list.

Example 4 — Write generic helpers for batches and windows

Section titled “Example 4 — Write generic helpers for batches and windows”

Goal: Mini-batch training and streaming dashboards need the same small helpers for any item type: the first item, fixed-size batches and a rolling window of the latest values. Write them once with type parameters so that mypy still knows the item type at every call.

Step 1 — Write the generic functions and class

Section titled “Step 1 — Write the generic functions and class”
batching.py
"""Generic helpers: the first item, mini-batches and a rolling window."""
from collections import deque
from collections.abc import Iterator, Sequence
def first[T](items: Sequence[T]) -> T:
"""Return the first item; its type is the item type of the sequence."""
return items[0]
def batches[T](items: Sequence[T], size: int) -> Iterator[list[T]]:
"""Yield lists of at most `size` items, in order."""
for start in range(0, len(items), size):
yield list(items[start : start + size])
class Window[T]:
"""Keep the last `size` items that were pushed."""
def __init__(self, size: int) -> None:
self.items: deque[T] = deque(maxlen=size)
def push(self, item: T) -> None:
self.items.append(item)
def latest(self) -> list[T]:
return list(self.items)

batches is a generator, so its return type is Iterator[list[T]]: an iterator that yields lists of T. Window[T] stores its items in a deque with maxlen, which drops the oldest item automatically (module 09). The attribute hint deque[T] is needed, because an empty deque alone tells the checker nothing about its items.

Step 2 — Use the helpers on readings and ids

Section titled “Step 2 — Use the helpers on readings and ids”
from batching import Window, batches, first
readings = [21.0, 21.9, 21.4, 21.7, 22.1]
customer_ids = ("C00001", "C00002", "C00003")
print(first(readings), first(customer_ids))
print(list(batches(customer_ids, 2)))
window = Window[float](3)
for value in readings:
window.push(value)
print(window.latest())
Output
21.0 C00001
[['C00001', 'C00002'], ['C00003']]
[21.4, 21.7, 22.1]

The same code works for floats and for strings. The window keeps only the last three readings.

batching_check.py
"""Ask mypy which types it infers for the generic helpers."""
from typing import reveal_type
from batching import Window, batches, first
readings = [21.0, 21.9, 21.4, 21.7, 22.1]
customer_ids = ("C00001", "C00002", "C00003")
reveal_type(first(readings))
reveal_type(first(customer_ids))
reveal_type(batches(customer_ids, 2))
window = Window[float](3)
for value in readings:
window.push(value)
reveal_type(window.latest())
window.push("22.4")
Output
Runtime type is 'float'
Runtime type is 'str'
Runtime type is 'generator'
Runtime type is 'list'
Terminal
mypy batching_check.py
Output
batching_check.py:10: note: Revealed type is "float"
batching_check.py:11: note: Revealed type is "str"
batching_check.py:12: note: Revealed type is "typing.Iterator[list[str]]"
batching_check.py:17: note: Revealed type is "list[float]"
batching_check.py:18: error: Argument 1 to "push" of "Window" has incompatible type "str"; expected
"float" [arg-type]
window.push("22.4")
^~~~~~
Found 1 error in 1 file (checked 1 source file)

Python saw only runtime classes: float, str, generator, list, and it accepted the string "22.4" in a window of floats. mypy saw the full types, such as list[float], and rejected the string. The type argument in Window[float](3) is what makes this work: an empty window has no items for the checker to infer from.

Step 4 — Compare with the older TypeVar form

Section titled “Step 4 — Compare with the older TypeVar form”
from collections.abc import Iterator, Sequence
from typing import TypeVar
T = TypeVar("T")
def batches_old(items: Sequence[T], size: int) -> Iterator[list[T]]:
for start in range(0, len(items), size):
yield list(items[start : start + size])
print(list(batches_old([21.0, 21.9, 21.4], 2)))
Output
[[21.0, 21.9], [21.4]]

The body is identical. Only the declaration of T differs: a module-level TypeVar("T") instead of [T] after the function name. In the new syntax, T exists only inside the function, so two functions cannot share or confuse it by accident.

Common mistakes:

  • Hinting a helper as Sequence[Any] -> Any. It runs, but every caller loses the item type and the checker goes quiet.
  • Creating an empty generic container without a type argument (Window(3)). mypy then asks for a hint (Need type annotation for "window"). Write Window[float](3).
  • Using a type parameter only once in a signature, such as def log[T](item: T) -> None. A type variable is useful only when it links two places. Write item: object instead.

Example 5 — Accept any model with fit and predict: Protocol

Section titled “Example 5 — Accept any model with fit and predict: Protocol”

Goal: An evaluation function must accept your own simple baseline models and scikit-learn models alike, without a shared base class. Describe “a regressor” as a Protocol, check two baselines on data/houses.csv, then plug in scikit-learn.

Step 1 — Define the protocol and two baseline models

Section titled “Step 1 — Define the protocol and two baseline models”
models.py
"""Any object with fit() and predict() can be evaluated: a Protocol."""
import csv
from collections.abc import Sequence
from statistics import mean, median
from typing import Protocol, Self, runtime_checkable
type Features = Sequence[Sequence[float]]
@runtime_checkable
class Regressor(Protocol):
def fit(self, X: Features, y: Sequence[float]) -> Self: ...
def predict(self, X: Features) -> list[float]: ...
class MeanRegressor:
"""Predict the mean training price for every house."""
def __init__(self) -> None:
self.mean_ = 0.0
def fit(self, X: Features, y: Sequence[float]) -> Self:
self.mean_ = mean(y)
return self
def predict(self, X: Features) -> list[float]:
return [self.mean_ for _ in X]
class PricePerSqftRegressor:
"""Predict size times the median price per square foot."""
def __init__(self) -> None:
self.rate_ = 0.0
def fit(self, X: Features, y: Sequence[float]) -> Self:
self.rate_ = median(price / row[0] for row, price in zip(X, y, strict=True))
return self
def predict(self, X: Features) -> list[float]:
return [row[0] * self.rate_ for row in X]
def mae(y_true: Sequence[float], y_pred: Sequence[float]) -> float:
return sum(abs(t - p) for t, p in zip(y_true, y_pred, strict=True)) / len(y_true)
def evaluate(model: Regressor, X: Features, y: Sequence[float], n_train: int) -> float:
"""Fit on the first n_train rows and return the MAE on the rest."""
model.fit(X[:n_train], y[:n_train])
return mae(y[n_train:], model.predict(X[n_train:]))
def load_houses(path: str) -> tuple[list[list[float]], list[float]]:
with open(path, encoding="utf-8", newline="") as f:
rows = list(csv.DictReader(f))
X = [[float(row["sqft"])] for row in rows]
y = [float(row["price"]) for row in rows]
return X, y
if __name__ == "__main__":
X, y = load_houses("data/houses.csv")
for model in (MeanRegressor(), PricePerSqftRegressor()):
print(f"{type(model).__name__:<22} MAE {evaluate(model, X, y, 2400):>10,.0f}")
Output
MeanRegressor MAE 225,400
PricePerSqftRegressor MAE 158,325

Neither model mentions Regressor. They match it by shape: both have fit and predict with the right signatures. Self (from typing) means “the class of this object”, so fit returns the model itself, as in scikit-learn, and model.fit(X, y).predict(X) works. The rows are sorted by sale date, so the first 2,400 houses train and the last 600 test. Price per square foot cuts the error of the naive mean model by about 30%.

Terminal
mypy --strict models.py
Output
Success: no issues found in 1 source file

Step 2 — Plug in scikit-learn without changes

Section titled “Step 2 — Plug in scikit-learn without changes”
from sklearn.linear_model import LinearRegression
from models import MeanRegressor, Regressor, evaluate, load_houses
X, y = load_houses("data/houses.csv")
print(isinstance(MeanRegressor(), Regressor), isinstance(LinearRegression(), Regressor))
print(isinstance([21.0, 21.9], Regressor))
print(f"LinearRegression MAE {evaluate(LinearRegression(), X, y, 2400):,.0f}")
Output
True True
False
LinearRegression MAE 154,798

@runtime_checkable allows isinstance() with a protocol. That check is shallow: it only tests that the methods fit and predict exist, not their signatures. A list has neither, so it fails. LinearRegression came from a library that knows nothing about Regressor, and it still plugs into evaluate. This is structural typing at work. (scikit-learn ships without full type hints, so mypy cannot check its signatures; this demo runs at runtime only.)

Step 3 — Let mypy reject a model that does not fit

Section titled “Step 3 — Let mypy reject a model that does not fit”
models_bad.py
"""A model whose method name does not match the Regressor protocol."""
from collections.abc import Sequence
from statistics import median
from typing import Self
from models import Features, evaluate, load_houses
class MedianRegressor:
def __init__(self) -> None:
self.median_ = 0.0
def fit(self, X: Features, y: Sequence[float]) -> Self:
self.median_ = median(y)
return self
def predict_one(self, row: Sequence[float]) -> float:
return self.median_
X, y = load_houses("data/houses.csv")
print(evaluate(MedianRegressor(), X, y, 2400))
Output
AttributeError: 'MedianRegressor' object has no attribute 'predict'
Terminal
mypy models_bad.py
Output
models_bad.py:23: error: Argument 1 to "evaluate" has incompatible type "MedianRegressor"; expected
"Regressor" [arg-type]
print(evaluate(MedianRegressor(), X, y, 2400))
^~~~~~~~~~~~~~~~~
models_bad.py:23: note: "MedianRegressor" is missing following "Regressor" protocol member:
models_bad.py:23: note: predict
Found 1 error in 1 file (checked 1 source file)

At runtime, the crash comes only after the model has been fitted, inside evaluate. mypy reports the problem at the call, and its notes name the missing member: predict.

Common mistakes:

  • Writing a body instead of ... in a protocol method. The body is never used for matching. Keep protocols as pure descriptions.
  • Trusting isinstance() with a runtime-checkable protocol as a full check. It ignores signatures and return types.
  • Making the protocol too large. Ask only for the methods your function calls. evaluate needs fit and predict, not score or get_params.

Example 6 — Add types to a legacy API script, step by step

Section titled “Example 6 — Add types to a legacy API script, step by step”

Goal: An old, untyped script summarizes the saved API page data/api/products_page_1.json. It crashes, and mypy says it is fine. Learn why, then add types one layer at a time: gradual typing.

legacy_products.py
"""An old, untyped script that summarizes one saved API page."""
import json
def load_page(path):
with open(path, encoding="utf-8") as f:
return json.load(f)
def in_stock_names(page):
return [item["name"] for item in page["data"] if item["in_stock"]]
def average_price(page):
prices = [item["price"] for item in page["data"]]
return round(sum(prices) / len(prices), 2)
page = load_page("data/api/products_page_1.json")
print(len(in_stock_names(page)), "products in stock")
print("Average price:", average_price(page))
Output
9 products in stock
TypeError: unsupported operand type(s) for +: 'int' and 'dict'

The first line prints. Then sum() fails: each price in the API response is a dict such as {"amount": 79.99, "currency": "USD"}, not a number.

Terminal
mypy legacy_products.py
mypy --strict legacy_products.py | tail -n 5
Output
Success: no issues found in 1 source file
legacy_products.py:22: error: Call to untyped function "average_price" in typed context
[no-untyped-call]
print("Average price:", average_price(page))
^~~~~~~~~~~~~~~~~~~
Found 6 errors in 1 file (checked 1 source file)

In normal mode, mypy skips the body of every function without hints, and json.load() returns Any anyway. “Success” here means “nothing to check”, not “correct”. Strict mode lists six problems (the command shows only the last of them with tail -n 5): three functions without hints and three calls to them. None of them is the real bug. To find it, the checker needs to know the shape of the data.

Step 3 — Describe the JSON and annotate the functions

Section titled “Step 3 — Describe the JSON and annotate the functions”
product_types.py
"""Types for the saved product pages in data/api/."""
import json
from pathlib import Path
from typing import Literal, TypedDict, cast
class Price(TypedDict):
amount: float
currency: Literal["USD"]
class Rating(TypedDict):
average: float
count: int
class Product(TypedDict):
id: str
name: str
category: str
price: Price
in_stock: bool
stock: int
rating: Rating
launch_date: str
url: str
class ProductPage(TypedDict):
page: int
per_page: int
total: int
total_pages: int
next: str | None
data: list[Product]
def load_page(path: Path) -> ProductPage:
with path.open(encoding="utf-8") as f:
return cast(ProductPage, json.load(f))
products_typed.py
"""The product summary with types: mypy now sees the bug."""
from pathlib import Path
from product_types import ProductPage, load_page
def in_stock_names(page: ProductPage) -> list[str]:
return [item["name"] for item in page["data"] if item["in_stock"]]
def average_price(page: ProductPage) -> float:
prices = [item["price"] for item in page["data"]]
return round(sum(prices) / len(prices), 2)
page = load_page(Path("data/api/products_page_1.json"))
print(len(in_stock_names(page)), "products in stock")
print("Average price:", average_price(page))
Output
9 products in stock
TypeError: unsupported operand type(s) for +: 'int' and 'dict'
Terminal
mypy products_typed.py
Output
products_typed.py:14: error: Argument 1 to "sum" has incompatible type "list[Price]"; expected
"Iterable[bool]" [arg-type]
return round(sum(prices) / len(prices), 2)
^~~~~~
Found 1 error in 1 file (checked 1 source file)

The types do not change what the code does, so it still crashes. But now mypy knows that prices is a list[Price] and reports the bug at the right line. The expected type Iterable[bool] looks odd: sum() has several overloaded signatures, and mypy names the first one. The message to take away is “a list of Price dicts is not a list of numbers”. next: str | None mirrors the JSON: the URL of the next page, or null on the last page.

products_fixed.py
"""The product summary with types, fixed."""
from pathlib import Path
from product_types import ProductPage, load_page
def in_stock_names(page: ProductPage) -> list[str]:
return [item["name"] for item in page["data"] if item["in_stock"]]
def average_price(page: ProductPage) -> float:
prices = [item["price"]["amount"] for item in page["data"]]
return round(sum(prices) / len(prices), 2)
page = load_page(Path("data/api/products_page_1.json"))
print(len(in_stock_names(page)), "products in stock")
print("Average price:", average_price(page))
Output
9 products in stock
Average price: 401.49
Terminal
mypy --strict products_fixed.py
Output
Success: no issues found in 1 source file

Page 1 lists 10 products. P006 is out of stock, so 9 are in stock. Their mean price is 401.49 USD.

Common mistakes:

  • Reading “Success” on an untyped file as “no bugs”. mypy checks only what has hints. Run mypy --strict on new code, or add --check-untyped-defs to check the bodies of old functions too.
  • Typing everything at once in a large project. Start at the data boundary (the loaders) and the most used functions. Each typed layer makes the next one easier.
  • Adding # type: ignore to make the report green. Fix the type, or name the error code and write a comment that says why.

Example 7 — Validate untrusted JSON at runtime

Section titled “Example 7 — Validate untrusted JSON at runtime”

Goal: data/api/users.json comes from an API that you do not control. The User TypedDict describes what the API promises, but hints check nothing at runtime. Write a validator that uses the type’s own information, then let pydantic do the same job.

Step 1 — See that a hint does not validate

Section titled “Step 1 — See that a hint does not validate”
import json
from typing import Literal, TypedDict
type Role = Literal["admin", "analyst"]
class User(TypedDict):
id: int
name: str
email: str
active: bool
roles: list[Role]
with open("data/api/users.json", encoding="utf-8") as f:
raw_users = json.load(f)
broken: User = {"id": "7", "name": "Test"} # wrong type, missing keys: runs anyway
print(type(raw_users).__name__, len(raw_users), broken)
Output
list 10 {'id': '7', 'name': 'Test'}

The annotation broken: User changes nothing at runtime. mypy would reject this line, but data from a file or an API never passes through the checker: it arrives at runtime as Any.

from typing import get_args, get_type_hints
print(sorted(User.__required_keys__))
print(get_type_hints(User)["roles"])
print(get_args(Role.__value__))
Output
['active', 'email', 'id', 'name', 'roles']
list[Role]
('admin', 'analyst')

Hints are objects, so code can read them. A TypedDict class knows its required keys. typing.get_type_hints() returns the hints of a class or function as a dict. typing.get_args() returns the type arguments of a hint, here the allowed role names. A type alias wraps its value, so ask for Role.__value__: get_args(Role) returns an empty tuple.

Step 3 — Write a validator at the boundary

Section titled “Step 3 — Write a validator at the boundary”
from typing import cast
def validate_user(raw: dict[str, object]) -> User:
"""Return the record as a User, or raise ValueError with the first problem."""
missing = User.__required_keys__ - raw.keys()
if missing:
raise ValueError(f"missing keys: {sorted(missing)}")
if not isinstance(raw["id"], int):
raise ValueError(f"id must be an int, got {raw['id']!r}")
allowed = get_args(Role.__value__)
roles = raw["roles"]
if not isinstance(roles, list) or not all(role in allowed for role in roles):
raise ValueError(f"unknown role in {roles!r}")
return cast(User, raw)
users = [validate_user(record) for record in raw_users]
print(len(users), "valid users;", sum(user["active"] for user in users), "active")
for bad in ({"id": 11, "name": "Kim"}, {**raw_users[0], "roles": ["owner"]}):
try:
validate_user(bad)
except ValueError as exc:
print("Rejected:", exc)
Output
10 valid users; 9 active
Rejected: missing keys: ['active', 'email', 'roles']
Rejected: unknown role in ['owner']

The validator is the boundary between the untyped outside world and the typed program. After it, cast is honest: the record was checked. Inside the program, the checker takes over. The validator reuses the types (__required_keys__, get_args), so the type and the check cannot drift apart. It checks only some of the fields; a full check of every field by hand is long.

Step 4 — Let pydantic read the hints for you

Section titled “Step 4 — Let pydantic read the hints for you”
from pydantic import TypeAdapter, ValidationError
adapter = TypeAdapter(User)
yuki = adapter.validate_python(raw_users[0])
print(yuki["name"], yuki["roles"])
try:
adapter.validate_python({**raw_users[0], "id": "seven", "roles": ["owner"]})
except ValidationError as exc:
for error in exc.errors():
print(error["loc"], error["msg"])
Output
Yuki Tanaka ['admin', 'analyst']
('id',) Input should be a valid integer, unable to parse string as an integer
('roles', 0) Input should be 'admin' or 'analyst'

pydantic is a library that validates data against type hints at runtime. TypeAdapter(User) reads the hints of the TypedDict and checks every key, type and literal value, with a precise location for each error (('roles', 0) is the first item of roles). FastAPI uses pydantic to validate every request. Module 44 uses it for model input.

Common mistakes:

  • Believing that user: User = json.load(f) validates the data. It is a promise to the checker, and nobody checks the promise.
  • Validating deep inside the program, in every function. Validate once, where the data enters, and trust the types after that.
  • Writing a long hand-made validator for a big schema. For more than a few fields, use pydantic.
Mistake Symptom Fix
Expecting Python to enforce hints Wrong types run; silent wrong results Run mypy; validate external data at runtime
A hint that lies, such as -> float for a function that can return None Errors on the wrong line, or a crash later Make the hint true: -> float | None
Using a X | None value without a check Item "None" of "X | None" has no attribute ... [union-attr] Narrow first: if x is None: ...
Passing list[int] where list[float] is expected incompatible type "list[int]"; expected "list[float]" Accept Sequence[float] or Iterable[float]
mypy says Success on old code Bugs remain in untyped functions Use --strict or --check-untyped-defs
dict[str, Any] for JSON records Typos in keys pass the check Write a TypedDict
Reading a NotRequired key with [] KeyError at runtime; mypy does not warn Use .get(key, default) or check key in record
cast on unchecked external data The checker trusts wrong data Validate first, then cast (or use pydantic)
A bare # type: ignore Hides future errors on the line # type: ignore[error-code] and fix it soon
Callable[..., float] everywhere Wrong-signature functions pass Spell out the parameters: Callable[[float], float]
An empty generic container without a type Need type annotation for "..." values: list[float] = [], Window[float](3)
get_args(Alias) on a type alias Returns () get_args(Alias.__value__)
from typing import List in new code Works, but ruff UP flags it Use list[...], dict[...]
  • Web APIs: FastAPI reads the hints of each endpoint function to parse and validate requests and to generate API documentation. A parameter limit: int = 10 becomes a validated query parameter.
  • Command-line tools: Typer builds a command-line interface from a typed function: def main(path: Path, top: int = 3) becomes --top 3 with type checks and help text.
  • Large codebases: Dropbox typed more than 4 million lines of Python with mypy, using gradual typing. Teams run the checker in continuous integration (CI), so a pull request with a type error cannot be merged.
  • Libraries: packages ship hints (marked by a py.typed file) so that their users get autocompletion and checks. The standard library’s hints live in a project called typeshed, which mypy and pyright both bundle.
  • A type hint says what a variable, parameter or return value should be. Python stores hints and ignores them at runtime; wrong types run silently.
  • A static type checker (mypy, pyright) reads the code and reports type bugs before it runs. Use mypy --strict for new code and read each report line as file, line, message and error code.
  • Use built-in generics (list[float], dict[str, list[int]]), abstract inputs (Sequence, Iterable, Mapping) and specific outputs.
  • Mark missing values with X | None and narrow them with is None checks before use.
  • Callable[[A, B], R] types functions as values. Literal[...] types a fixed set of options.
  • TypedDict describes JSON records key by key, with NotRequired for keys that may be missing. At runtime it is a plain dict.
  • Generics keep the item type: def first[T](items: Sequence[T]) -> T, class Box[T]. Old code uses T = TypeVar("T") and Generic[T]. type Name = ... creates an alias.
  • A Protocol matches any class with the right methods: structural typing for “anything with fit and predict”.
  • cast and @overload help the checker. cast checks nothing. Validate untrusted data at the boundary, by hand or with pydantic.

Q1. A function has the hint def scale(values: list[float]) -> list[float]. You call it with a variable that holds a list of strings. What happens when the code runs, and what does mypy do?

Answer

Python runs the call as if the hint were not there. The function either fails on the first operation that strings do not support (with a TypeError somewhere inside) or returns a wrong result. mypy reads the code without running it and reports Argument 1 to "scale" has incompatible type "list[str]"; expected "list[float]" [arg-type] at the call.

Q2. What is the difference between Any and object as a parameter type?

Answer

Both accept every value. With Any, the checker stops checking: every operation on the value is allowed. With object, the checker allows only what every object can do, so you must narrow the value with isinstance() before you use it. object is safe; Any switches the checker off.

Q3. Why is Sequence[float] a better parameter hint than list[float] for a function that only reads its input?

Answer

It accepts more callers: lists, tuples and ranges. And it accepts a list[int], which list[float] rejects because list is invariant (the function could append a float to a list of ints). Sequence is read-only, so that risk does not exist.

Q4. A function find_customer(customer_id: str) -> Customer | None returns None when no customer matches. Why does find_customer("C00001")["name"] fail the check, and how do you fix it?

Answer

The result can be None, and None has no ["name"]. mypy reports Value of type "Customer | None" is not indexable. Store the result and narrow it first: customer = find_customer("C00001"), then if customer is None: ... (return, raise or use a default), then customer["name"].

Q5. What does cast(ProductPage, json.load(f)) do at runtime?

Answer

Nothing. cast returns its second argument unchanged and checks nothing. It only tells the checker to treat the value as a ProductPage from then on. If the file does not match, the program still gets the wrong data.

Q6. In data/customers.json, postal_code is missing in some addresses and phone is sometimes null. Which hints describe these two keys, and why are they different?

Answer

postal_code: NotRequired[str] and phone: NotRequired[str | None]. NotRequired says the key may be absent. | None says the key may be present with the value null (which json.load turns into None). phone can be absent or null, so it needs both.

Q7. Rewrite this in the modern syntax: T = TypeVar("T") and def last(items: Sequence[T]) -> T: return items[-1].

Answer

def last[T](items: Sequence[T]) -> T: return items[-1]. The type parameter goes in brackets after the function name, and no TypeVar import or module-level variable is needed. It requires Python 3.12 or newer.

Q8. Your function evaluate(model: Regressor, ...) uses a Regressor Protocol with fit and predict. A colleague’s class has these two methods but does not inherit from Regressor. Does mypy accept it? Why?

Answer

Yes, if the method signatures match. A Protocol uses structural typing: a class matches by its methods and attributes, not by its inheritance. The class does not even need to import Regressor.

Q9. mypy legacy.py prints Success: no issues found in 1 source file, but the script crashes with a TypeError. How can both be true?

Answer

By default, mypy does not check the bodies of functions without hints, and values from json.load() are Any, which is never checked. Success means “nothing I could check was wrong”. mypy --strict reports the missing hints; after you add hints (for example a TypedDict for the JSON), mypy finds the bug.

Q10. When should a parameter be Literal["mean", "median"] instead of str?

Answer

When only a few fixed values are valid, as for an imputation strategy or a metric name. The checker then rejects typos such as "meen" at the call, editors offer the valid values, and the hint documents the options. Use str when any text is valid, such as a customer name.

Q11. Name two libraries that use type hints at runtime, and say what they do with them.

Answer

pydantic validates and converts data against the hints (for example TypeAdapter(User).validate_python(record)). FastAPI uses the hints of endpoint functions, through pydantic, to validate requests and document the API. Dataclasses and Typer read hints too.

Your progress

0 / 4 done

  • Exercises: 26 exercises with hints and full solutions, from annotating a function to typing a decorator and a paginated API client.
  • Mini-project: type a churn-scoring module for data/customers.csv until mypy --strict passes.
  • Cheat sheet: every hint, typing tool and mypy command of this module on one page.
  • Next module: 13. Pythonic code teaches idioms, EAFP vs LBYL, PEP 8 and ruff, and the classic Python gotchas.