Type hints
What Python 3.14 does with annotations at run time and when it evaluates them, how to write types — unions, generics, Protocol, TypedDict, Literal, Self — and what mypy finds before the program runs.
Types in prose
The topic Modules, packages and environments ended with a project whose pyproject.toml lists every dependency and its version, so anyone can install what the code needs. The functions inside the project still do not say what they need. Does tax take a float or a string? Can find return None? Which keys must a config dict have? A reader learns it from the docstring, from the body, or from a crash.
Here is the docstring way. find looks a word up in a small vocabulary:
def find(words, target):
"""Return the position of target in words (a list of str), or None."""
for i, w in enumerate(words):
if w == target:
return i
return None
vocab = ["the", "cat", "sat"]
print(find(vocab, "cat") + 1)
print(find(vocab, "dog") + 1)The traceback is shortened:
2
Traceback (most recent call last):
...
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'The docstring warned that None can come back, and nothing read the docstring. The + 1 line works on every run where the word is in the list and fails on the first day it is not.
Type hints write the same facts into the code in a notation that tools can read:
def find(words: list[str], target: str) -> int | None: ...A type checker is a separate program that reads the source code and reports where it disagrees with the hints, without running anything. This topic shows what Python 3.14 itself does with hints (very little, and later than before), how to write the types that come up in ML code, and what a checker, mypy, finds before the program runs.
Stored, not enforced
An annotation is an expression attached with a colon to a parameter or a variable, or with an arrow to the return value:
def area(width: float, height: float) -> float:
return width * height
print(area(3, 4))
print(area("ab", 3))
print(area.__annotations__)
count: int = "not a number"
print(count)
total: int
print(total)12
ababab
{'width': <class 'float'>, 'height': <class 'float'>, 'return': <class 'float'>}
not a number
Traceback (most recent call last):
...
NameError: name 'total' is not definedPython does not check annotations. They do not change what the code does when it runs, so area("ab", 3) repeats the string three times, exactly as it would without them.
Read the output line by line. area(3, 4) returns the integer 12. By a rule of the type system an int is accepted where a float is annotated, and nothing converts it. The annotations live in the dict __annotations__, the return type under the key 'return'. count: int = ... is an ordinary assignment plus an annotation. total: int without a value binds nothing, so the name stays undefined.
Annotations are stored on the function, class or module, and tools read them from there. A type checker reads them before the program runs. Libraries read them while it runs: the Config dataclass from the topic Classes and objects got its fields from exactly these annotations.
Lazy annotations in 3.14
When does Python evaluate an annotation expression? Up to Python 3.13, when the def runs. So a function could not name a class defined further down the file, unless you wrote the name as a string, "Node". Since Python 3.14 (PEP 649 and PEP 749), annotations are evaluated lazily:
def link(node: Node) -> Node | None:
return node.next
class Node:
def __init__(self, value: int) -> None:
self.value = value
self.next: Node | None = None
print(link.__annotations__){'node': <class '__main__.Node'>, 'return': __main__.Node | None}On Python 3.13 the same file stops at its first line with NameError: name 'Node' is not defined. Did you mean: 'None'?. In 3.14 the def evaluates nothing. The compiler has turned the annotations into a small function, stored as link.__annotate__. The first read of link.__annotations__ calls it, now that Node exists, and caches the dict.
So an annotation that names something undefined is harmless until someone reads it. The module annotationlib can still return the annotations as source text:
import annotationlib
def broken(x: Undefined) -> int:
return 1
print(broken(5))
print(annotationlib.get_annotations(broken, format=annotationlib.Format.STRING))
print(broken.__annotations__)1
{'x': 'Undefined', 'return': 'int'}
Traceback (most recent call last):
...
NameError: name 'Undefined' is not definedThe default format, Format.VALUE, evaluates and may raise. Format.FORWARDREF evaluates what it can and leaves a placeholder where a name is missing. Libraries such as dataclasses use these formats.
An annotation with a side effect shows when the evaluation happens:
evaluations = 0
def counted():
global evaluations
evaluations += 1
return int
def f(x: counted()) -> None: ...
print("after def:", evaluations)
f.__annotations__
f.__annotations__
print("after two reads:", evaluations)after def: 0
after two reads: 1In older code you will meet from __future__ import annotations (Python 3.7). It turns every annotation in the module into a string. It still works in 3.14, and new code does not need it. A type checker evaluates nothing at all: it reads the source text.
Writing types
Types are written with a small vocabulary that combines freely:
| Annotation | Means |
|---|---|
int, str, Vector |
an instance of that class or a subclass |
list[float], dict[str, int], set[str] |
a container with elements of these types |
tuple[int, str], tuple[float, ...] |
a pair of an int and a str; a tuple of floats of any length |
int | None |
an int or None (older spelling: Optional[int]) |
Iterable[str], Sequence[float], Mapping[str, int] |
anything with that protocol, from collections.abc |
Callable[[int], float] |
a function that takes an int and returns a float |
Any |
anything; the checker stops checking |
Two habits make hints useful rather than restrictive.
- Accept protocols, return concrete types. A function that only loops over its argument should take
Iterable[float], notlist[float], so callers can pass a tuple, a set or a generator. It should return a concretedict[str, int], so callers know what they can do with the result. This is the duck typing of the topic The data model, written down. - Say
Nonewhen it can happen. The most common bug that checkers find is a value that may beNoneused as if it were always there.-> int | Nonemakes every caller handle the absent case.
Both habits on the running examples, a list of losses and a word count:
from collections.abc import Iterable
def mean_loss(losses: Iterable[float]) -> float:
total, n = 0.0, 0
for x in losses:
total, n = total + x, n + 1
return total / n
def count_words(words: Iterable[str]) -> dict[str, int]:
counts: dict[str, int] = {}
for w in words:
counts[w] = counts.get(w, 0) + 1
return counts
print(mean_loss((0.5, 0.25, 0.75)), count_words("the cat saw the dog".split()))0.5 {'the': 2, 'cat': 1, 'saw': 1, 'dog': 1}mean_loss counts the items itself instead of calling len. An iterable promises only that it can be looped over, not that it knows its length.
Generics
A generic function works with many types and keeps them consistent. first returns an element of whatever sequence it gets. Its hint should say that the result has the element type of the argument. A type parameter in square brackets after the name says exactly that (PEP 695, Python 3.12):
from collections.abc import Sequence
def first[T](items: Sequence[T]) -> T:
return items[0]
type Pair[T] = tuple[T, T]
print(first([0.9, 0.7]), first("abc"), first.__type_params__)
print(type(first.__type_params__[0]), Pair.__value__)0.9 a (T,)
<class 'typing.TypeVar'> tuple[T, T][T] declares a type variable for this function. A checker solves for T at each call. In first([0.9, 0.7]), T is float, so the result is a float. A str is a sequence of str, so first("abc") is a str. The type statement makes an alias; its value is lazy, like annotations.
A class takes type parameters the same way:
class Stack[T]:
def __init__(self) -> None:
self.items: list[T] = []
def push(self, x: T) -> None:
self.items.append(x)
def pop(self) -> T:
return self.items.pop()
s = Stack[int]()
s.push(1)
s.push("two")
print(s.items)[1, 'two']At run time T is a TypeVar object and nothing more, so Stack[int] took "two" without complaint. mypy rejects that line:
stack.py:11: error: Argument 1 to "push" of "Stack" has incompatible type "str"; expected "int" [arg-type]A type parameter can have a bound. def most_common[K: Hashable](items: Iterable[K]) -> K accepts words or numbers, and a checker rejects a list of lists, because a list is not hashable. In libraries you will meet the older spelling of the same idea: T = TypeVar("T") at module level and class Stack(Generic[T]).
Protocols
The topic The data model gave two ways to describe "anything with an area method": duck typing, which no tool can check, and an abstract base class, which every class must inherit from. A protocol (PEP 544) is a third way. It lists the methods, and every class that has them matches, with no inheritance. This is structural typing; ordinary classes use nominal typing, where only declared subclasses match.
A learning-rate schedule is anything with a method lr(step):
from typing import Protocol, runtime_checkable
@runtime_checkable
class Schedule(Protocol):
def lr(self, step: int) -> float: ...
class Halving:
def lr(self, step: int) -> float:
return 0.1 / 2 ** step
def lrs(schedule: Schedule, n: int) -> list[float]:
return [schedule.lr(t) for t in range(n)]
print(lrs(Halving(), 4), isinstance(Halving(), Schedule), isinstance("adam", Schedule))[0.1, 0.05, 0.025, 0.0125] True FalseHalving never mentions Schedule, and it still matches. A checker verifies the match from the class definition: the method must exist and its signature must fit. @runtime_checkable also lets isinstance test the protocol at run time, but that test is much weaker. It only checks that an attribute with each listed name exists.
Protocols are how hints describe Python's own duck typing. For a checker, Iterable, Sized and Hashable from collections.abc act as protocols: Sized means "has __len__", whatever the class.
TypedDict, Literal and Self
Three more tools cover patterns that come up in every ML project.
TypedDict describes a dict with fixed keys, each with its own type, such as a config loaded from JSON or YAML. Literal restricts a value to a few exact constants. NotRequired marks a key that may be absent:
from typing import Literal, NotRequired, TypedDict, get_args
class RunConfig(TypedDict):
lr: float
epochs: int
optimizer: Literal["sgd", "adam"]
seed: NotRequired[int]
cfg: RunConfig = {"lr": 3e-4, "epochs": 10, "optimizer": "adam"}
print(cfg, type(cfg))
print(sorted(RunConfig.__required_keys__), sorted(RunConfig.__optional_keys__))
print(get_args(RunConfig.__annotations__["optimizer"])){'lr': 0.0003, 'epochs': 10, 'optimizer': 'adam'} <class 'dict'>
['epochs', 'lr', 'optimizer'] ['seed']
('sgd', 'adam')At run time cfg is a plain dict, unlike an instance of the Config dataclass. A checker compares every dict literal annotated RunConfig with the class: missing keys, extra keys, and values of the wrong type are errors. A misspelt "adamw" is caught long before the code that dispatches on the optimizer name fails.
Self is the type of the object a method was called on. A method that returns self, like scikit-learn's fit, should be annotated with it:
from typing import Self
class Model:
def __init__(self) -> None:
self.mean = 0.0
def fit(self, xs: list[float]) -> Self:
self.mean = sum(xs) / len(xs)
return self
class Centerer(Model):
def transform(self, xs: list[float]) -> list[float]:
return [x - self.mean for x in xs]
print(Centerer().fit([1.0, 2.0, 3.0]).transform([2.0, 4.0]))[0.0, 2.0]Called on a Centerer, fit returns a Centerer as far as the checker knows, so the chained .transform is accepted.
What a checker finds
A checker reads the hints and the code together. This file collects two mistakes from this topic:
from collections.abc import Iterable
def find(words: list[str], target: str) -> int | None:
for i, w in enumerate(words):
if w == target:
return i
return None
def mean_loss(losses: Iterable[float]) -> float:
n = len(losses)
return sum(losses) / n
vocab = ["the", "cat", "sat"]
print(find(vocab, "cat") + 1, mean_loss([0.5, 0.25]))Python runs it and prints 2 0.375. Both lines work today. mypy 2.4.1 on Python 3.14.7 (installed with uv add --dev mypy, as in the previous topic) reports both mistakes without running anything:
$ mypy check.py
check.py:10: error: Argument 1 to "len" has incompatible type "Iterable[float]"; expected "Sized" [arg-type]
check.py:14: error: Unsupported operand types for + ("None" and "int") [operator]
check.py:14: note: Left operand is of type "int | None"
Found 2 errors in 1 file (checked 1 source file)Each error names the line, the expected and the actual types, and a code in brackets. Line 10 fails the day someone passes a generator. Line 14 fails the day the word is missing. The fixes are a Sequence[float] parameter, which promises a length, and a check if pos is not None: before the + 1; after that check the checker knows pos is an int. A comment # type: ignore[arg-type] silences one error on one line, for the rare case when you know better.
Typing is gradual. By default mypy does not check the body of a function without annotations, so a project can start with its most used modules. Other checkers: pyright from Microsoft, which VS Code runs as you type, and the newer, faster Pyrefly from Meta and ty from Astral, the makers of uv. Pick one per project and run it in continuous integration.
What checkers cannot know: array shapes, ranges of numbers, file contents. Above all, they cannot know whether the result is right. A mean_loss that divides by len(losses) + 1 passes mypy with no errors and returns the wrong number. That closes the Abstraction module: classes and the data model define types, closures and decorators change behaviour, modules organize code, and hints state what each function expects. The next topic, Testing, checks what the code actually computes.
Check your understanding
The same questions as in Pulse. Answers are shared between modes.
Answers are saved on the server and tied to this browser until you sign in.