Type hints
Type hints describe what a function takes and returns. Python stores them and ignores them at runtime. A static type checker such as mypy or pyright reads them and finds bugs before the code runs. This page uses the Python 3.12+ syntax.
Quick lookup
Section titled “Quick lookup”| I want to… | Use… | Example |
|---|---|---|
| hint parameters and the return value | name: T, -> R |
def mean(xs: list[float]) -> float: |
| say “returns nothing” | -> None |
def log(msg: str) -> None: |
| hint an empty container | a variable annotation | rows: list[dict[str, str]] = [] |
allow None |
T | None |
def find(cid: str) -> Customer | None: |
| allow several types | a union A | B |
value: int | float | str |
| a fixed-length tuple / any length | tuple[str, float] / tuple[float, ...] |
def span() -> tuple[int, int]: |
| accept any iterable or sequence | Iterable[T], Sequence[T] |
def total(xs: Iterable[float]) -> float: |
| accept any read-only mapping | Mapping[K, V] |
def show(cfg: Mapping[str, object]) -> None: |
| type a generator | Iterator[T] or Generator[Y, S, R] |
def lines(p: Path) -> Iterator[str]: |
| type a callback | Callable[[A, B], R] |
on_done: Callable[[str], None] |
| allow only some constant values | Literal[...] |
mode: Literal["r", "w"] |
| type a JSON-like dict | TypedDict |
class Order(TypedDict): order_id: str |
| a key that may be absent | NotRequired[T] |
phone: NotRequired[str] |
| name a long type | type alias |
type Row = dict[str, str | float] |
| keep the item type through a function | a type parameter | def first[T](xs: Sequence[T]) -> T: |
| a generic class | class Name[T]: |
class Stack[T]: |
| limit a type parameter | a bound or constraints | def top[N: float](xs: list[N]) -> N: |
| accept “anything with method m” | Protocol |
class Readable(Protocol): def read(self) -> str: ... |
| return the instance’s own class | Self |
def fit(self, X) -> Self: |
| keep a decorated function’s signature | ParamSpec via [**P, R] |
def timed[**P, R](f: Callable[P, R]) -> Callable[P, R]: |
| several signatures for one function | @overload |
def get(k: str) -> str: ... |
| a constant that is never reassigned | Final |
MAX_RETRIES: Final = 3 |
| a class-level attribute | ClassVar[T] |
registry: ClassVar[dict[str, type]] = {} |
| mark a method as an override | @override (3.12+) |
@override def run(self) -> None: |
| narrow with your own check | TypeIs[T] (3.13+), TypeGuard[T] |
def is_str(x: object) -> TypeIs[str]: |
| prove every case is handled | assert_never(x) |
the else of a match or if chain |
| a function that never returns | NoReturn (or Never) |
def fail(msg: str) -> NoReturn: raise SystemExit(msg) |
| an async callback | Callable[[str], Awaitable[None]] |
on_page: Callable[[int], Coroutine[Any, Any, str]] |
| only literal strings (SQL, shell) | LiteralString |
def run(sql: LiteralString) -> None: (pyright enforces it; mypy treats it as str) |
| a type you know but the checker does not | cast(T, value) |
cast(Config, json.load(f)) |
| imports only for hints | if TYPE_CHECKING: |
avoids import cycles and slow imports |
| a distinct type for ids | NewType |
UserId = NewType("UserId", int) |
| extra metadata on a type | Annotated[T, meta] |
Annotated[int, Field(gt=0)] (pydantic) |
| silence one checker error | # type: ignore[code] |
x = legacy() # type: ignore[no-untyped-call] |
| check a project | mypy src/ |
mypy --strict src/ |
Syntax table (Python 3.12+)
Section titled “Syntax table (Python 3.12+)”| Feature | Modern syntax | Old spelling (still valid) |
|---|---|---|
| built-in generics | list[int], dict[str, float], set[str], tuple[int, ...] |
typing.List[int], Dict, Set, Tuple |
| optional | str | None |
Optional[str] |
| union | int | str |
Union[int, str] |
| callables | collections.abc.Callable[[int], str] |
typing.Callable |
| abstract containers | collections.abc.Iterable, Sequence, Mapping, Iterator |
typing.Iterable and others |
| literal values | Literal["mean", "median"] |
|
| a dict with known keys | class Order(TypedDict): ... |
TypedDict("Order", {...}) |
| a structural interface | class P(Protocol): ... |
|
| type alias | type Matrix = list[list[float]] |
Matrix: TypeAlias = list[list[float]] |
| generic function | def first[T](xs: list[T]) -> T: |
T = TypeVar("T") |
| bound | def f[N: float](x: N) -> N: |
TypeVar("N", bound=float) |
| constrained | def f[S: (str, bytes)](x: S) -> S: |
TypeVar("S", str, bytes) |
| generic class | class Box[T]: |
class Box(Generic[T]): |
| generic alias | type Pair[T] = tuple[T, T] |
|
| parameter spec | def deco[**P, R](f: Callable[P, R]) -> Callable[P, R]: |
P = ParamSpec("P") |
| variadic generics | def f[*Ts](*args: *Ts) -> tuple[*Ts]: |
TypeVarTuple("Ts") |
| type parameter default (3.13+) | class Box[T = int]: |
TypeVar("T", default=int) |
| own class | Self |
a bound TypeVar |
typed **kwargs |
**kwargs: Unpack[Options] with a TypedDict |
|
| deprecation marker (3.13+) | @warnings.deprecated("use g()") |
Import abstract types from collections.abc. Import Literal, TypedDict, Protocol, Self, Final, ClassVar, cast, overload, TYPE_CHECKING and friends from typing.
Functions, variables and unions
Section titled “Functions, variables and unions”from collections.abc import Iterable, Iterator, Sequence
def mean(xs: Sequence[float]) -> float: # accept general input return sum(xs) / len(xs)
def parse(values: Iterable[str]) -> list[float | None]: # return specific output return [float(v) if v.strip() else None for v in values]
def chunks(xs: list[int], size: int = 2) -> Iterator[list[int]]: for i in range(0, len(xs), size): yield xs[i : i + size]
def label(code: str | None) -> str: if code is None: # the checker narrows code to str below return "none" return code.upper()
print(mean([3, 4.5]), parse(["21.5", " "]), list(chunks([1, 2, 3])), label(None))print(mean.__annotations__) # hints are stored, not enforced3.75 [21.5, None] [[1, 2], [3]] none{'xs': collections.abc.Sequence[float], 'return': <class 'float'>}| Hint | Accepts | Note |
|---|---|---|
float |
float and int |
int is accepted where float is expected |
list[float] |
a list of floats | invariant: a list[int] variable is rejected |
Sequence[float] |
a list, tuple or range of floats or ints | read-only and covariant: list[int] is fine; a str is a Sequence[str] |
Iterable[T] |
anything you can loop over once | generators, files, sets |
Mapping[str, V] |
any dict-like, read-only | use dict[str, V] when you mutate |
object |
anything; allows nothing until narrowed | a safe “any value” |
Any |
anything; allows everything | switches checking off |
type[Model] |
the class itself, not an instance | factories |
Rule of thumb: accept general types (Iterable, Sequence, Mapping), return specific ones (list, dict).
Records: TypedDict, Literal and Final
Section titled “Records: TypedDict, Literal and Final”from typing import Final, Literal, NotRequired, TypedDict, get_type_hints
type Channel = Literal["online", "store"]TAX_RATE: Final = 0.2 # mypy flags any reassignment
class Order(TypedDict): order_id: str channel: Channel revenue: float coupon: NotRequired[str] # the key may be absent
order: Order = {"order_id": "O000001", "channel": "online", "revenue": 66.49}print(order.get("coupon", "none"), type(order).__name__) # a plain dict at runtimeprint(sorted(Order.__required_keys__), sorted(Order.__optional_keys__))print(get_type_hints(Order)["revenue"], Channel.__value__)none dict['channel', 'order_id', 'revenue'] ['coupon']<class 'float'> typing.Literal['online', 'store']| TypedDict need | Write |
|---|---|
| every key required (default) | class R(TypedDict): ... |
| one key may be absent | key: NotRequired[T] |
| most keys optional | class R(TypedDict, total=False): plus key: Required[T] |
| key present but may be null | key: T | None |
| a read-only key (3.13+) | key: ReadOnly[T] |
| a key that is not an identifier | R = TypedDict("R", {"user-id": str}) |
Callable, ParamSpec and decorators
Section titled “Callable, ParamSpec and decorators”import timefrom collections.abc import Callablefrom functools import wraps
type Metric = Callable[[list[float], list[float]], float]
def mae(y: list[float], p: list[float]) -> float: return sum(abs(a - b) for a, b in zip(y, p, strict=True)) / len(y)
def timed[**P, R](func: Callable[P, R]) -> Callable[P, R]: # keeps the signature @wraps(func) def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: start = time.perf_counter() try: return func(*args, **kwargs) finally: print(f"{func.__name__} ran: {time.perf_counter() - start >= 0}") return wrapper
@timeddef evaluate(y: list[float], p: list[float], metric: Metric = mae) -> float: return round(metric(y, p), 3)
print(evaluate([3.0, 5.0], [2.5, 5.5]), timed.__type_params__)evaluate ran: True0.5 (P, R)| Form | Means |
|---|---|
Callable[[int, str], bool] |
two positional parameters, returns bool |
Callable[[], None] |
no parameters, returns nothing |
Callable[..., R] |
any parameters |
Callable[P, R] with [**P, R] |
the same parameters as the wrapped function |
Callable[Concatenate[Request, P], R] |
one extra first parameter, then P |
a Protocol with __call__ |
keyword names or overloads that Callable cannot express |
Generics with PEP 695
Section titled “Generics with PEP 695”from collections.abc import Sequence
def first[T](items: Sequence[T]) -> T: # T is bound per call return items[0]
def largest[N: (int, float)](values: Sequence[N]) -> N: # constrained return max(values)
class Stack[T]: def __init__(self) -> None: self._items: list[T] = []
def push(self, item: T) -> None: self._items.append(item)
def pop(self) -> T: return self._items.pop()
type Pair[T] = tuple[T, T] # a generic aliass = Stack[str]()s.push("P001")print(first(("S01", "S02")), largest([3, 25, 1]), s.pop(), Pair.__type_params__)S01 25 P001 (T,)Protocol, Self and overload
Section titled “Protocol, Self and overload”from typing import Protocol, Self, overload, runtime_checkable
@runtime_checkableclass Model(Protocol): def fit(self, X: list[list[float]], y: list[float]) -> Self: ... def predict(self, X: list[list[float]]) -> list[float]: ...
class MeanModel: # no inheritance: matches by shape def fit(self, X: list[list[float]], y: list[float]) -> Self: self.mean_ = sum(y) / len(y) return self
def predict(self, X: list[list[float]]) -> list[float]: return [self.mean_] * len(X)
def score(model: Model, X: list[list[float]], y: list[float]) -> list[float]: return model.fit(X, y).predict(X)
@overloaddef to_f(c: float) -> float: ...@overloaddef to_f(c: list[float]) -> list[float]: ...def to_f(c: float | list[float]) -> float | list[float]: # the real implementation if isinstance(c, list): return [round(x * 9 / 5 + 32, 1) for x in c] return round(c * 9 / 5 + 32, 1)
print(score(MeanModel(), [[1.0], [2.0]], [10.0, 20.0]), isinstance(MeanModel(), Model))print(to_f(21.5), to_f([19.0, 23.0]))[15.0, 15.0] True70.7 [66.2, 73.4]Protocol |
abc.ABC |
|
|---|---|---|
| matches | by shape (structural) | by inheritance (nominal) |
| third-party classes | match without changes | must inherit or be registered |
| shared code | none | can provide methods |
runtime isinstance |
with @runtime_checkable; checks method names only |
yes |
The full comparison, with collections.abc and registration, is on the ABC vs Protocol page.
ClassVar, Final, cast and TYPE_CHECKING
Section titled “ClassVar, Final, cast and TYPE_CHECKING”import jsonfrom dataclasses import dataclass, fieldfrom typing import TYPE_CHECKING, ClassVar, Final, TypedDict, cast
if TYPE_CHECKING: # False at runtime: the import costs nothing from decimal import Decimal
class Config(TypedDict): version: str
@dataclassclass Job: name: str count: ClassVar[int] = 0 # shared by the class, not a dataclass field tags: list[str] = field(default_factory=list) limit: Final[int] = 3 # a dataclass field that mypy will not let you reassign
def cost(self, rate: "Decimal") -> "Decimal": # quoted: not imported at runtime return rate * self.limit
raw = json.loads('{"version": "1.4.0"}') # json gives Anyconfig = cast(Config, raw) # no check, no conversion: returns raw unchangedprint(config is raw, Job("load"), Job.count, TYPE_CHECKING)True Job(name='load', tags=[], limit=3) 0 False| Tool | Effect for the checker | Effect at runtime |
|---|---|---|
cast(T, v) |
treats v as T |
returns v unchanged |
TYPE_CHECKING |
True |
False |
Final |
no reassignment, no override | none |
ClassVar[T] |
a class attribute; not a dataclass field | dataclasses skip it |
@overload |
several signatures | only the last definition runs |
@override |
error if the parent has no such method | sets __override__ |
reveal_type(x) |
prints the inferred type | prints the runtime type to stderr |
assert_never(x) |
error if a case is reachable | raises AssertionError |
from __future__ import annotations |
none | hints stay unevaluated strings (3.14 defers them by default) |
Narrowing
Section titled “Narrowing”| Check | Narrows x: str | int | None |
Note |
|---|---|---|
if x is None: return |
str | int after the if |
the clearest form |
isinstance(x, str) |
str inside |
works with tuples of types |
if x: |
drops None, but also "" and 0 |
careful with numbers |
match x: case str(): |
str in that case |
pattern matching narrows too |
a TypeIs[str] function (3.13+) |
str when it returns True; also narrows the else branch |
your own reusable check |
a TypeGuard[str] function |
str only when it returns True; no else narrowing |
the type may be unrelated to the input (list[object] → list[str]) |
assert x is not None |
not None after it |
for “cannot happen” cases |
mypy commands
Section titled “mypy commands”These commands run in a terminal, in an environment where mypy is installed (uv add --dev mypy).
mypy script.py # check one file and what it importsmypy src/ tests/ # check foldersmypy --strict src/ # every strict flag: hints required, no Any leaksmypy --check-untyped-defs old.py # also check bodies of functions without hintsmypy --pretty --show-error-codes . # source line with markers, [code] at the endmypy --python-version 3.12 src/ # check against an older Pythonmypy --ignore-missing-imports src/ # quiet "missing stubs" for untyped librariesmypy --install-types # install missing stub packages (types-requests)dmypy run -- src/ # mypy daemon: fast re-checkspyright src/ # Microsoft's checker, also inside VS Code Pylance[tool.mypy]python_version = "3.12"strict = true # same as --strict on every runwarn_unreachable = true # code after return or impossible branchespretty = truefiles = ["src", "tests"] # what a bare `mypy` checks
[[tool.mypy.overrides]]module = ["sklearn.*", "joblib.*"] # libraries without type hintsignore_missing_imports = true
[[tool.mypy.overrides]]module = ["tests.*"]disallow_untyped_defs = false # relax rules for test files| Error code | Meaning | Typical fix |
|---|---|---|
arg-type |
an argument has the wrong type | convert it, or fix the hint |
return-value |
the return value does not match -> |
return the right type or widen the hint |
assignment |
a value does not fit the variable’s type | |
union-attr |
attribute access on X | None |
narrow with is None first |
call-arg |
missing or unexpected argument | |
index |
wrong key type | |
typeddict-item |
unknown key or wrong value type in a TypedDict | |
var-annotated |
an empty container needs a hint | xs: list[str] = [] |
no-untyped-def |
a function without hints (strict) | add hints |
no-any-return |
returns Any from a typed function (strict) |
cast or validate |
import-untyped |
a library without type information | install stubs (types-...) or an override |
override |
a method’s signature breaks the parent’s | match the parent’s parameters |
A report line reads file.py:27: error: <message> [code]. The last line says Found N errors in M files or Success: no issues found in N source files.
Gotchas
Section titled “Gotchas”| Trap | Symptom | Fix |
|---|---|---|
| hints are not checked at runtime | n: int = "3" runs without an error |
run mypy; validate untrusted data with pydantic |
| unannotated functions | mypy says Success but checks nothing inside | --strict or --check-untyped-defs |
| invariance | list[int] rejected where list[float] is expected |
accept Sequence[float] |
Optional[X] means “may be None” |
not “optional argument” | write X | None; a default makes it optional |
if x: as a None check |
0, 0.0 and "" take the wrong branch |
if x is not None: |
cast |
a wrong cast hides a real bug | validate first, then cast |
json.load returns Any |
no errors for any key or type | a TypedDict plus validation |
a bare # type: ignore |
hides every future error on that line | # type: ignore[code] |
a list[T] = [] default |
the shared mutable default bug | x: list[T] | None = None |
get_args(Alias) on a type alias |
returns () |
get_args(Alias.__value__) |
isinstance with a protocol |
checks only that method names exist | real checks in the method |
bool is a subtype of int |
True passes as int |
test isinstance(x, bool) first |
| PEP 695 syntax on Python 3.11 or older | SyntaxError |
use TypeVar and Generic there |
| forward reference to a later class | NameError at import on 3.12/3.13 |
quote it ("Node") or from __future__ import annotations |
| untyped libraries | import-untyped; values become Any |
an override in pyproject.toml, or stub packages |
Learn more
Section titled “Learn more”- Module 12 lesson: type hints and its cheat sheet
- Module 11: decorators and context managers for
ParamSpecdecorators - Module 13: Pythonic code for linting in the same workflow
- OOP sheets: ABC vs Protocol, data containers
- Master cheat sheet: tooling, pytest