Course contents 14 / 22

14 / 22 · Abstraction

Type hints

What annotations are and what Python 3.14 does with them at run time, including their deferred evaluation; how to write types: unions, generics with the 3.12 syntax, Protocol, TypedDict, Literal and Self; and what the checkers mypy and pyright find before a program runs.

On this page 10

The previous note gave a project a declared list of dependencies, so that anyone can install what the code needs. The functions inside the project still do not declare what they need. Whether tax takes a float or a string, whether find can return None, which keys a configuration dictionary must have: a reader learns it from documentation, from the body, or from a crash. Type hints write that information into the code, in a notation that tools can read. This note shows what an annotation is and what Python 3.14 does with it when the program runs, which is very little and, since 3.14, later than before; how to write the types that come up in practice, from unions to generics and protocols; and what a type checker does with them before the program runs.

Conventions. A type checker is a separate program that reads the source code and reports inconsistencies between the annotations and the code, without running it. The ones named here are mypy and pyright; their versions are given where their output is shown.

Baseline: types in docstrings#

Without hints, the types live in prose:

def find(words, target):
    """Return the position of target in words (a list of str), or None if absent."""
    for i, w in enumerate(words):
        if w == target:
            return i
    return None

A caller who writes find(words, "b") + 1 gets a program that works on every test where the word is present, and fails with TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' on the day it is not. The docstring said so, and nothing read the docstring. The same information as annotations, def find(words: list[str], target: str) -> int | None, can be read by a checker, which reports the + 1 line before the program ever runs, as the section on checkers shows.

Annotations: stored, not enforced#

An annotation is an expression attached to a parameter, a return value or a variable with a colon or an arrow:

def area(width: float, height: float) -> float:
    return width * height
>>> area(3, 4)
12
>>> area("ab", 3)
'ababab'
>>> area.__annotations__
{'width': <class 'float'>, 'height': <class 'float'>, 'return': <class 'float'>}
>>> count: int = "not a number"
>>> count
'not a number'
>>> total: int
>>> total
Traceback (most recent call last):
  ...
NameError: name 'total' is not defined

Read the session line by line. area(3, 4) returns the integer 12: an int is accepted where float is annotated, by the convention of the type system, and nothing converts it. area("ab", 3) violates the annotation and runs anyway. The annotations are kept in a dictionary, __annotations__. A variable annotation with a value, count: int = ..., is an ordinary assignment plus an annotation; without a value, total: int binds nothing, which is why total is still undefined.

Lazy annotations in Python 3.14#

When are the annotation expressions evaluated? Until Python 3.13, when the def ran. A function could therefore not mention a class defined further down the file without writing the name as a string, "Node". Since Python 3.14 (PEP 649 and PEP 749), annotations are evaluated lazily: the def stores a small function that computes them, and the computation runs when something asks for the annotations.

def link(node: Node) -> Node | None:
    return node.next

class Node:
    def __init__(self, value: int):
        self.value = value
        self.next: Node | None = None
>>> link.__annotations__
{'node': <class '__main__.Node'>, 'return': __main__.Node | None}
Figure

What happens to annotations in Python 3.14

Five stages in the life of an annotationFive boxes from top to bottom: def stores __annotate__ without evaluating; the class Node is defined later; accessing __annotations__ evaluates the dict; annotationlib returns strings or ForwardRef objects; a type checker reads the text without running it.def runs: annotations are not evaluateddef link(node: Node) -> Node | None:__annotate__: a function, not yet run1class Node is defined laterclass Node: ...2first access evaluates and cacheslink.__annotations__→ {'node': Node, 'return': Node | None}3other formats, without evaluatingget_annotations(link, format=STRING)→ {'node': 'Node', 'return': …}FORWARDREF: ForwardRef if undefined4a type checker reads the sourcemypy, pyright: no code runserrors come before the program runs5Five stages in the life of an annotationFive boxes from top to bottom: def stores __annotate__ without evaluating; the class Node is defined later; accessing __annotations__ evaluates the dict; annotationlib returns strings or ForwardRef objects; a type checker reads the text without running it.def runs: annotations are not evaluateddef link(node: Node) -> Node | None:__annotate__: a function, not yet run1class Node is defined laterclass Node: ...2first access evaluates and cacheslink.__annotations__→ {'node': Node, 'return': Node | None}3other formats, without evaluatingget_annotations(link, format=STRING)→ {'node': 'Node', 'return': …}FORWARDREF: ForwardRef if undefined4a type checker reads the sourcemypy, pyright: no code runserrors come before the program runs5
Deferred evaluation of annotations (PEP 649 and PEP 749), on the example of the note. When def runs, the annotations are not evaluated: the compiler stores a function __annotate__ that will evaluate them later (1). That is why an annotation can refer to the class Node, defined after the function (2). The first access to link.__annotations__ calls __annotate__ and caches the resulting dict (3). The module annotationlib can return the same annotations as strings or ForwardRef objects, evaluating nothing (4). A type checker such as mypy or pyright reads the source text and never runs it (5). Green marks code, blue what is stored at run time, amber the ways to read annotations, red the static check.
  1. When def link runs, the annotations are not evaluated. The compiler has turned them into a function, stored as link.__annotate__, so the name Node is not needed yet.
  2. class Node is defined afterwards.
  3. The first access to link.__annotations__ calls __annotate__, evaluates the expressions, now that Node exists, and caches the dictionary.
  4. The new module annotationlib can return the annotations in other formats without evaluating them, which tools need when some names do not exist at run time.
  5. A type checker never evaluates anything: it reads the source text.

The rule has consequences that can be seen directly. An annotation that names something undefined is harmless until it is read, and an annotation with a side effect runs it once, on first access:

def broken(x: Undefined) -> int:
    return 1
>>> broken(5)
1
>>> broken.__annotations__
Traceback (most recent call last):
  ...
NameError: name 'Undefined' is not defined
>>> import annotationlib
>>> annotationlib.get_annotations(broken, format=annotationlib.Format.STRING)
{'x': 'Undefined', 'return': 'int'}
>>> annotationlib.get_annotations(broken, format=annotationlib.Format.FORWARDREF)
{'x': ForwardRef('Undefined', owner=<function broken at 0x106398b40>), 'return': <class 'int'>}

Format.VALUE, the default, evaluates and may raise. Format.FORWARDREF evaluates what it can and puts a ForwardRef placeholder where a name is missing. Format.STRING returns the source text of each annotation. Libraries that inspect annotations, such as dataclasses, use these formats so that a class can refer to types defined later.

The older mechanism. from __future__ import annotations (PEP 563, Python 3.7) makes every annotation in the module a string, {'x': 'Undefined', 'return': 'int'}, and you meet it in much existing code. It still works in 3.14; the reference says it will be deprecated and removed, but not before Python 3.13 reaches its end of life (PEP 749). New code for 3.14 does not need it.

Writing types#

The vocabulary is a small set of rules, combined freely (PEP 484 and its successors):

AnnotationMeansSince
int, str, Vectoran instance of that class or a subclass3.5
list[int], dict[str, float], set[str]a container with elements of the given types3.9 (PEP 585)
tuple[int, str], tuple[float, ...]a pair of an int and a str; a tuple of any length of floats3.9
int | Nonean int or None (the older spelling is Optional[int])3.10 (PEP 604)
Sequence[str], Iterable[int], Mapping[str, int]anything with that protocol, from collections.abc3.9
Callable[[int, str], bool]a function taking an int and a str, returning a bool3.9
Anyanything; the checker stops checking3.5

Two habits make annotations useful rather than restrictive:

  • Accept protocols, return concrete types. A function that only loops over its argument should take Iterable[str], not list[str], so that callers can pass a tuple, a set or a generator; it should return a concrete list[str], so that callers know what they can do with the result. This is duck typing from the data model note, written down.
  • Say None when it can happen. Most real bugs that checkers find are a possibly-None value used as if it were always there. -> int | None forces every caller to handle the absent case.

Generics with the 3.12 syntax#

A generic function works with many types but keeps them consistent. first returns an element of whatever sequence it is given; its annotation should say that the result has the element type of the argument. A type parameter in square brackets after the name does that (PEP 695, Python 3.12):

from collections.abc import Sequence

def first[T](items: Sequence[T]) -> T:
    return items[0]

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()

type Pair[T] = tuple[T, T]
>>> first([3, 1, 2]), first("abc")
(3, 'a')
>>> first.__type_params__
(T,)
>>> type(first.__type_params__[0])
<class 'typing.TypeVar'>
>>> type(Pair), Pair.__value__, Pair[int]
(<class 'typing.TypeAliasType'>, tuple[T, T], Pair[int])
>>> s = Stack[int]()
>>> s.push(1); s.push("two")
>>> s.items
[1, 'two']

The rules:

  • [T] declares a type variable for that function or class. A checker solves for T at each call: in first([3, 1, 2]), T is int and the result is an int; in first("abc"), a str is a sequence of str, so the result is a str. At run time T is a TypeVar object and nothing more, which is why Stack[int] accepted "two" without complaint. A checker would reject that line.
  • Bounds and constraints. [H: Hashable] restricts T to subtypes of Hashable, a bound. [N: (int, float)] restricts it to exactly one of the listed types, a constraint, so that biggest(1, 2.5) must pick one type for both arguments. Since Python 3.13 a type parameter can have a default, [T = int] (PEP 696).
  • type makes an alias, type Vec = list[float]. Its value is evaluated lazily, like annotations, so an alias may refer to itself, type Tree = list[Tree] | int, or to names defined later.

The 3.12 syntax replaces an older spelling that you will meet in libraries: T = TypeVar("T") at module level, then def first(items: Sequence[T]) -> T, and class Stack(Generic[T]). The two mean the same.

Structural typing with Protocol#

The data model note offered 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 or register with. A protocol (PEP 544, Python 3.8) is the third way: it describes the methods, and any class that has them matches, with no inheritance. The checker verifies the match from the class’s definition. This is structural typing, as opposed to the nominal typing of ordinary classes, where only declared subclasses match.

from typing import Protocol, runtime_checkable

@runtime_checkable
class SupportsArea(Protocol):
    def area(self) -> float: ...

class Square:
    def __init__(self, side: float) -> None:
        self.side = side
    def area(self) -> float:
        return self.side ** 2

class Label:
    text = "hi"

def total_area(shapes: list[SupportsArea]) -> float:
    return sum(s.area() for s in shapes)
>>> isinstance(Square(2), SupportsArea), isinstance(Label(), SupportsArea)
(True, False)
>>> total_area([Square(1), Square(2)])
5

Square never mentions SupportsArea and still matches it. @runtime_checkable additionally lets isinstance test the protocol at run time, by checking only that the methods exist, not their signatures. Protocols are how type hints describe Python’s own duck typing: collections.abc.Iterable, Sized and Hashable act as protocols for checkers, and NumPy’s ArrayLike is a union of the many things that can be turned into an array.

TypedDict, Literal and Self#

Three more tools cover common patterns.

TypedDict (PEP 589) describes a dictionary with fixed keys, each with its own type, such as a configuration loaded from JSON or YAML. At run time it is an ordinary dict:

from typing import TypedDict, NotRequired, Literal

class RunConfig(TypedDict):
    lr: float
    epochs: int
    optimizer: Literal["sgd", "adam"]
    seed: NotRequired[int]
>>> cfg: RunConfig = {"lr": 3e-4, "epochs": 10, "optimizer": "adam"}
>>> cfg, type(cfg)
({'lr': 0.0003, 'epochs': 10, 'optimizer': 'adam'}, <class 'dict'>)
>>> sorted(RunConfig.__required_keys__), sorted(RunConfig.__optional_keys__)
(['epochs', 'lr', 'optimizer'], ['seed'])
>>> bad: RunConfig = {"lr": "fast"}
>>> bad
{'lr': 'fast'}

A checker rejects bad: mypy 1.7.0 reports the missing keys epochs and optimizer, and, once they are added, the str given for lr. Python stores it as it is. NotRequired (PEP 655, Python 3.11) marks a key that may be absent.

Literal (PEP 586) restricts a value to a few exact constants: Literal["sgd", "adam"] accepts those two strings and no others. It documents string options that functions dispatch on, and a checker catches a misspelt "adamw" long before the dispatch fails at run time. typing.get_args returns the allowed values, ('sgd', 'adam'), so code can validate them at run time too.

Self (PEP 673, Python 3.11) is the type of the instance a method was called on. A method that returns self for chaining, annotated -> Self, then returns the subclass type when called on a subclass:

from typing import Self

class Builder:
    def __init__(self) -> None:
        self.parts: list[str] = []
    def add(self, part: str) -> Self:
        self.parts.append(part)
        return self

class LoudBuilder(Builder):
    def shout(self) -> Self:
        self.parts = [p.upper() for p in self.parts]
        return self
>>> LoudBuilder().add("a").add("b").shout().parts
['A', 'B']

Without Self, add would be annotated -> Builder, and a checker would reject .shout() on its result, because Builder has no shout. scikit-learn’s fit, which returns self, is the familiar case.

Type checkers#

A checker reads the annotations and the code together and reports every place where they disagree. Here is a file that collects the mistakes of this note:

# check.py: the definitions of area, find, SupportsArea, Square, Label and total_area
# from this note, RunConfig as in the Code section (no epochs key), followed by:
area("ab", 3)
position = find(["a", "b"], "b") + 1
total_area([Square(1), Label()])
cfg: RunConfig = {"lr": 3e-4, "optimizer": "adamw"}

mypy reports four errors without running anything (mypy 1.7.0, the version installed on the machine used for this course, told to assume Python 3.12 because it predates 3.14; the file uses no newer syntax):

$ mypy --python-version 3.12 check.py
check.py:40: error: Argument 1 to "area" has incompatible type "str"; expected "float"  [arg-type]
check.py:41: error: Unsupported operand types for + ("None" and "int")  [operator]
check.py:41: note: Left operand is of type "int | None"
check.py:42: error: List item 1 has incompatible type "Label"; expected "SupportsArea"  [list-item]
check.py:43: error: Incompatible types (expression has type "Literal['adamw']", TypedDict item "optimizer" has type "Literal['sgd', 'adam']")  [typeddict-item]
Found 4 errors in 1 file (checked 1 source file)

Running the same file with Python tells a different story. Line 40 returns 'ababab', line 41 works because "b" happens to be in the list, and the program stops at line 42 with AttributeError: 'Label' object has no attribute 'area', inside total_area. Line 43 is never reached, and would not fail if it were. The checker found all four in one pass, including the two that would have run silently.

Each error names the line, the expected and the actual type, and a code in brackets; # type: ignore[arg-type] on a line silences that one error when you know better than the checker. The common checkers, as of 22 October 2026:

  • mypy, the oldest of them, started by Jukka Lehtosalo; release 2.4.0 on 1 October 2026.
  • pyright, from Microsoft, the engine behind the Pylance extension of VS Code; release 1.1.414 on PyPI on 10 September 2026. Editors run it as you type.
  • Newer, faster checkers written in Rust: Pyrefly from Meta (1.4.0, marked stable) and ty from Astral, the makers of uv (0.0.90, in beta).

The checkers agree on most programs and differ in details and defaults, such as how strictly they treat unannotated code. Pick one per project, run it in continuous integration with the tests of the next note, and annotate gradually: a checker checks only the functions that have annotations, so a project can start from its most used modules.

What checkers cannot know. Shapes of arrays, ranges of numbers, the contents of files: a float annotation does not say “between 0 and 1”, and np.ndarray does not say “of shape (batch, 784)”. Such properties are checked at run time with assertions, or with libraries that read annotations at run time, below.

Where ML code uses type hints#

  • Configuration objects are dataclasses or TypedDicts, and libraries such as pydantic read the annotations at run time to validate and convert a configuration file, which is exactly the run-time check that Python itself does not do. The Code section writes a ten-line version of that idea.
  • Library signatures. PyTorch, NumPy (numpy.typing.ArrayLike, NDArray[np.float32]) and Hugging Face annotate their public functions, which is what makes editor completion and documentation precise.
  • Shapes in annotations. Libraries such as jaxtyping write array shapes and dtypes into annotations, Float[Tensor, "batch 784"], and can check them at run time; standard type checkers treat them as opaque.

What changed#

Types in docstrings (the baseline)Type hints
Where types are writtenprose, in any formannotations, in a standard notation
Effect when the program runsnonenone, apart from storage and tools that read them
When annotations are evaluated—lazily, on first access (3.14)
Who checks themnobodya type checker, before the program runs
None returned on some pathsa surprise at run timea reported error at every unsafe use
Generic and duck-typed codedescribed in wordstype parameters and protocols

Limitations#

  • Type hints are a gradual system: unannotated code and Any are not checked, and a checker is only as strict as its configuration.
  • The note leaves out ParamSpec and Concatenate for annotating decorators, TypeIs and TypeGuard for narrowing functions, overloads, variance, Final, ClassVar, and @override (3.12). The typing specification documents them.
  • The mypy output shown is from an older release run on this machine; newer releases may word the messages differently or add notes.
  • Run-time evaluation of annotations follows PEP 649 and PEP 749 as implemented in CPython 3.14; code that must also run on 3.13 or older cannot rely on lazy evaluation.

What you should remember#

  • An annotation is stored, not enforced: Python runs area("ab", 3) as if there were none.
  • Since 3.14 annotations are evaluated lazily, on first access to __annotations__; annotationlib reads them as values, forward references or strings.
  • Write X | None when None can come back, accept protocols such as Iterable[T], return concrete types.
  • def f[T](x: T) -> T and class C[T] declare type parameters (3.12); type Alias = ... makes a lazy alias.
  • Protocol checks structure, not inheritance; TypedDict types a dictionary’s keys; Literal restricts a value to constants; Self types methods that return the instance.
  • A checker (mypy, pyright, Pyrefly, ty) reads the source and finds mismatches before the program runs; run it in CI and annotate gradually.

Code#

The script shows everything Python itself does with type hints, which is storage, lazy evaluation and introspection, and ends with a small decorator that does what Python does not: it checks arguments against simple annotations on every call. It needs only the standard library and Python 3.14, because of the lazy annotations and the 3.12 syntax; run it with python -I hints.py. A type checker is a separate tool and is not run here.

"""Type hints at run time in Python 3.14: storage, lazy evaluation, generics, Protocol, TypedDict, a checker."""
import annotationlib
import functools
import inspect
from collections.abc import Sequence
from dataclasses import dataclass
from typing import Literal, NotRequired, Protocol, Self, TypedDict, get_args, runtime_checkable

# 1. Annotations are stored, not enforced
def area(width: float, height: float) -> float:
    return width * height

print(area(3, 4), area("ab", 3), area.__annotations__)

# 2. Lazy evaluation (PEP 649/749): a function may name a class defined later
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__)

def broken(x: Undefined) -> int:         # fine until someone asks for the annotations
    return 1

print(broken(5))
print("STRING", annotationlib.get_annotations(broken, format=annotationlib.Format.STRING))
refs = annotationlib.get_annotations(broken, format=annotationlib.Format.FORWARDREF)
print("FORWARDREF", {name: type(v).__name__ for name, v in refs.items()}, refs["x"].__forward_arg__)
try:
    broken.__annotations__
except NameError as err:
    print("NameError:", err)

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)

# 3. Generics with the 3.12 syntax, and lazily evaluated type aliases
def first[T](items: Sequence[T]) -> T:
    return items[0]

type Pair[T] = tuple[T, T]
type Tree = list[Tree] | int             # a recursive alias: fine, the value is lazy

class Stack[T]:
    def __init__(self) -> None:
        self.items: list[T] = []
    def push(self, x: T) -> Self:
        self.items.append(x)
        return self

print(first([3, 1, 2]), first("abc"), first.__type_params__, Pair.__value__, Tree.__value__)
print(Stack[int]().push(1).push("two").items)    # no check at run time

# 4. Protocol: structural typing; runtime_checkable allows isinstance (method names only)
@runtime_checkable
class SupportsArea(Protocol):
    def area(self) -> float: ...

class Square:
    def __init__(self, side: float) -> None:
        self.side = side
    def area(self) -> float:
        return self.side ** 2

class Label:
    text = "hi"

print(isinstance(Square(2), SupportsArea), isinstance(Label(), SupportsArea))

# 5. TypedDict and Literal: at run time, a plain dict and a tuple of allowed values
class RunConfig(TypedDict):
    lr: float
    optimizer: Literal["sgd", "adam"]
    seed: NotRequired[int]

cfg: RunConfig = {"lr": 3e-4, "optimizer": "adamw"}      # a checker rejects "adamw"; Python does not
print(type(cfg).__name__, sorted(RunConfig.__required_keys__), get_args(RunConfig.__annotations__["optimizer"]))

# 6. Tools read annotations at run time: dataclasses, and a small checking decorator
@dataclass
class Run:
    lr: float
    tags: list[str]

print(Run("fast", "not a list"))          # dataclass uses the names, not the types

def checked(func):
    """Check arguments against plain-class annotations on every call."""
    sig = inspect.signature(func)
    hints = annotationlib.get_annotations(func)
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        for name, value in sig.bind(*args, **kwargs).arguments.items():
            expected = hints.get(name)
            if isinstance(expected, type) and not isinstance(value, expected):
                raise TypeError(f"{name}={value!r} is not {expected.__name__}")
        return func(*args, **kwargs)
    return wrapper

@checked
def scale(x: float, k: int) -> float:
    return x * k

print(scale(1.5, 2))
try:
    scale(1.5, "2")
except TypeError as err:
    print("TypeError:", err)

# Output with CPython 3.14.7 on macOS (arm64):
# 12 ababab {'width': <class 'float'>, 'height': <class 'float'>, 'return': <class 'float'>}
# {'node': <class '__main__.Node'>, 'return': __main__.Node | None}
# 1
# STRING {'x': 'Undefined', 'return': 'int'}
# FORWARDREF {'x': 'ForwardRef', 'return': 'type'} Undefined
# NameError: name 'Undefined' is not defined
# after def: 0
# after two reads: 1
# 3 a (T,) tuple[T, T] list[Tree] | int
# [1, 'two']
# True False
# dict ['lr', 'optimizer'] ('sgd', 'adam')
# Run(lr='fast', tags='not a list')
# 3.0
# TypeError: k='2' is not int

“after def: 0” and “after two reads: 1” are lazy evaluation in two numbers: defining f evaluated nothing, the first read of __annotations__ evaluated the annotation once, and the second read used the cached dictionary. The checked decorator is deliberately naive: it handles only plain classes, and it would reject scale(2, 2) because the integer 2 is not a float, although the type system accepts an int where a float is expected. Run-time validation libraries implement those rules properly.

Next#

This note closes the Abstraction section: classes and the data model to define types, closures and decorators to change behaviour, modules and environments to organize and install code, and type hints to state what each function expects. A checker catches mismatches of types, but not wrong results: a function with perfect annotations can still compute the wrong mean. The next note starts the Reliable Code section with tests, written with pytest, that check what the code computes.

References#