Objective
Type hints let a static checker find a class of bugs (a possibly missing value used as a number, a wrong field name, a function passed the wrong kind of object) before the code runs. By the end of this lesson you should be able to annotate a module, run mypy on it, read each error and fix it properly rather than silencing it. All outputs below are from mypy 2.4 on Python 3.11.
What annotations are, and are not
def mid(bid: float, ask: float) -> float: records the intended types. Python ignores them at run time: mid("a", "b") still runs (and fails, or worse, succeeds, inside). A checker such as mypy (or pyright) reads the annotations and checks every call and assignment against them. Two consequences:
- Annotations are documentation that cannot drift out of date, because the checker enforces them in CI.
- They give no run-time protection. Validate external input (files, JSON, network) explicitly at the boundary, then rely on types inside.
The everyday vocabulary, in modern syntax (Python 3.10+):
| Annotation | Meaning |
|---|---|
list[float], dict[str, int], tuple[str, float] | built-in containers with element types |
tuple[float, ...] | a tuple of any length |
float | None | a float or None (the old spelling is Optional[float]) |
Sequence[float], Mapping[str, float], Iterable[T] | read-only abstract interfaces from collections.abc |
Callable[[float], float] | a function from float to float |
Any | opt out of checking for this value |
Annotate parameters and returns; mypy infers most local variables.
Worked example
a None that reaches arithmetic
Run mypy on this file (spread.py) and fix what it reports.
def best_bid(bids: dict[str, list[float]], symbol: str) -> float | None:
levels = bids.get(symbol)
if not levels:
return None
return max(levels)
def spread(bids: dict[str, list[float]], ask: float, symbol: str) -> float:
bid = best_bid(bids, symbol)
return ask - bid
Show solutionHide solution
$ mypy spread.py
spread.py:10: error: Unsupported operand types for - ("float" and "None") [operator]
spread.py:10: note: Right operand is of type "float | None"
Found 1 error in 1 file (checked 1 source file)
Read it in three parts: the location (line 10, the subtraction), the problem (one possible type of the right operand does not support -), and the error code in brackets (operator), which is what you would name in a targeted # type: ignore[operator] if you ever had to. The note shows the inferred type of bid.
The bug is real: a symbol with an empty book would raise TypeError at run time, perhaps months later. Fix it by narrowing: after an is None check, mypy knows the type is float. reveal_type (understood by mypy, no import needed for the checker) shows this:
def spread(bids: dict[str, list[float]], ask: float, symbol: str) -> float:
bid = best_bid(bids, symbol)
reveal_type(bid)
if bid is None:
raise ValueError(f"no bids for {symbol}")
reveal_type(bid)
return ask - bid
spread_fixed.py:10: note: Revealed type is "float | None"
spread_fixed.py:13: note: Revealed type is "float"
Success: no issues found in 1 source file
(Remove reveal_type calls before running the code; at run time it is only defined from Python 3.11 via typing.reveal_type.) Other narrowing forms: isinstance(x, float), early return, and assert x is not None when you can prove it cannot be None. Do not write if bid: when 0.0 is a valid value; it narrows too, but it also treats a zero bid as missing.
Generics, Protocols and TypedDict
Generics relate input and output types. TypeVar says "whatever type comes in, the same type goes out":
T = TypeVar("T")
def last(xs: Sequence[T]) -> T:
return xs[-1]
last([1.5, 2.5]) has type float; last(["a"]) has type str. (Python 3.12 adds the shorter def last[T](xs: Sequence[T]) -> T.)
Protocols give structural typing ("duck typing, checked"): any class with the right methods matches, without inheriting from anything. This is how you type a plug-in interface such as "something that can price", so the analytics layer can accept a Black–Scholes pricer, a Monte Carlo pricer or a test fake without importing any of them.
TypedDict types a dictionary with fixed string keys, which is what you get from JSON or a database row. Prefer a dataclass for your own objects; use TypedDict where the data really is a dict at the boundary.
The file shapes.py below contains three deliberate mistakes:
from collections.abc import Sequence
from typing import Protocol, TypedDict, TypeVar
T = TypeVar("T")
def last(xs: Sequence[T]) -> T:
return xs[-1]
class Fill(TypedDict):
symbol: str
price: float
qty: int
class Pricer(Protocol):
def price(self, strike: float) -> float: ...
class Intrinsic: # never mentions Pricer
def price(self, strike: float) -> float:
return max(100.0 - strike, 0.0)
class Broken:
def price(self, strike: str) -> float:
return 0.0
def total(p: Pricer, strikes: list[float]) -> float:
return sum(p.price(k) for k in strikes)
n: int = last([1.5, 2.5])
f: Fill = {"symbol": "AAPL", "price": 190.0, "qty": "100"}
total(Intrinsic(), [90.0, 95.0])
total(Broken(), [90.0])
$ mypy shapes.py
shapes.py:35: error: Incompatible types in assignment (expression has type "float", variable has type "int") [assignment]
shapes.py:36: error: Incompatible types (expression has type "str", TypedDict item "qty" has type "int") [typeddict-item]
shapes.py:38: error: Argument 1 to "total" has incompatible type "Broken"; expected "Pricer" [arg-type]
shapes.py:38: note: Following member(s) of "Broken" have conflicts:
shapes.py:38: note: Expected:
shapes.py:38: note: def price(self, strike: float) -> float
shapes.py:38: note: Got:
shapes.py:38: note: def price(self, strike: str) -> float
Found 3 errors in 1 file (checked 1 source file)
Line 35: the TypeVar bound T to float, so the result cannot go into an int. Line 36: the quantity is the string "100", the classic CSV bug. Line 38: Broken has a price method, but with the wrong parameter type, and mypy prints both signatures. Line 37 passes: Intrinsic matches Pricer purely by shape. Note that python shapes.py runs to completion without any error, which is the point: none of these mistakes is visible at run time until the wrong value reaches arithmetic.
Worked example
list[int] is not a list[float]
mypy accepts an int wherever a float is expected. Predict what it says about this file, and fix it.
from collections.abc import Sequence
def mean(xs: list[float]) -> float:
return sum(xs) / len(xs)
def mean_ro(xs: Sequence[float]) -> float:
return sum(xs) / len(xs)
sizes: list[int] = [100, 200, 300]
mean(sizes)
mean_ro(sizes)
Show solutionHide solution
variance.py:13: error: Argument 1 to "mean" has incompatible type "list[int]"; expected "list[float]" [arg-type]
variance.py:13: note: "list" is invariant -- see https://mypy.readthedocs.io/en/stable/common_issues.html#variance
variance.py:13: note: Consider using "Sequence" instead, which is covariant
Found 1 error in 1 file (checked 1 source file)
The reasoning: a function that accepts list[float] is allowed to do xs.append(0.5). If you could pass a list[int], the caller's list of ints would then contain a float. So list is invariant: list[int] and list[float] are unrelated types. A read-only Sequence cannot be appended to, so it is safely covariant: a Sequence[int] is a Sequence[float]. Line 14 therefore passes.
The general rule: accept the most abstract read-only type you need (Sequence, Mapping, Iterable) and return the concrete type you built (list, dict). Callers can then pass lists, tuples or NumPy-backed sequences, and get the full interface back.
Running mypy in a real project
By default mypy does not check the body of a function that has no annotations, and treats calls to it as returning Any. This file passes:
def add(a, b):
return a + b
add(1, "x")
$ mypy untyped.py
Success: no issues found in 1 source file
$ mypy --strict untyped.py
untyped.py:1: error: Function is missing a type annotation [no-untyped-def]
untyped.py:5: error: Call to untyped function "add" in typed context [no-untyped-call]
Found 2 errors in 1 file (checked 1 source file)
and the program raises TypeError when run. "mypy passes" means little on unannotated code. Practical setup:
- Put the settings in
pyproject.tomlunder[tool.mypy], withstrict = truefor new packages; on a legacy codebase start withcheck_untyped_defs = trueand tighten per module with[[tool.mypy.overrides]]. - Run it in CI next to the tests, so a type error blocks a merge.
- Watch for
Anyleaking in:json.loadsreturnsAny, and so does an untyped third-party library. Convert to a typed object at the boundary. - Use
# type: ignore[code]with the specific error code and a comment, never a bare ignore;warn_unused_ignores(part of strict) tells you when it is no longer needed. - NumPy ships its own types (
numpy.typing.NDArray[np.float64]); pandas types are available through thepandas-stubspackage. Array shapes are not checked.
Knowledge check
A function is annotated def vwap(prices: list[float], sizes: list[float]) -> float and a caller passes sizes as a list[int]. What does mypy do, and what is the best fix?
Knowledge check
A legacy module has no annotations anywhere, and mypy (default settings) reports 'Success: no issues found'. What does that tell you?
Knowledge check
You want analytics code to accept any object with a method price(self, strike: float) -> float, including test fakes, without those classes importing or inheriting from anything. What do you annotate the parameter with?
Key takeaways
- Annotations are checked statically by mypy and ignored at run time; validate external input at the boundary.
- Read a mypy error as location, problem, error code; fix
X | Noneby narrowing (is Nonecheck, early return), not by ignoring. TypeVarlinks input and output types;Protocoltypes interfaces structurally;TypedDicttypes dict-shaped boundary data.- Mutable containers are invariant: accept
Sequence/Mapping/Iterable, return concrete types. - Default mypy skips unannotated functions; use
strict(or at leastcheck_untyped_defs) in CI and specific# type: ignore[code]only.
Finished reading?
Answer the 3 knowledge checks to complete this lesson (0 done).