Advanced Python Type Hints: Generics, Protocols and ParamSpec

An examination of advanced type hints in Python, from the generic syntax of Python 3.12 with bounds and constraints to protocols, callables and ParamSpec, with the deferred annotations of Python 3.14 and the limits of runtime checks.

Two green pythons with white markings, one coiled on a wooden branch in the foreground and another resting on a rock behind it.
Photo by Taylor Kopel on Unsplash

Annotations such as name: str or -> int describe simple values well, but real code is rarely that simple: functions return the same type they receive, classes hold elements of any type, objects are accepted for their behaviour rather than their ancestry, and decorators must preserve the signature of the function they wrap. The typing system of Python has a precise vocabulary for each of these situations, and Python 3.12 made the most common of them considerably shorter. The present article examines generic functions and classes, bounds and constraints, protocols and callables, the typing of decorators, and the relationship between annotations and the running program, including the deferred evaluation introduced by Python 3.14. A type checker that understands these constructs is the secret weapon that turns annotations into detected errors.

Generic Functions

A function that returns the first element of a sequence works for any element type, and annotating it with Any discards exactly the information that matters, namely that a sequence of strings yields a string. A type variable expresses that relationship, and Python 3.12 introduced a dedicated syntax for it (PEP 695): the type parameters are declared in square brackets after the name of the function.

from collections.abc import Sequence

def first[T](items: Sequence[T]) -> T:
    if not items:
        raise ValueError("empty sequence")
    return items[0]

print(first([3, 1, 2]))        # Output: 3
print(first(("a", "b")))       # Output: a
print(first.__type_params__)   # Output: (T,)

Online role-playing games offer a useful image for a type variable: some items bind to the first character that picks them up, and from that moment they belong to that character and to no other. In the same way, T binds at each call to the type of the elements received, so a type checker infers int for the first call and str for the second; the image ends there, because the binding lasts only for one call and is renewed at the next. The parameter is annotated as Sequence[T] rather than list[T] so that tuples are accepted as well. Before Python 3.12 the same function required a module-level declaration, T = TypeVar("T"), which still works and remains necessary for code that must run on older versions.

Bounds, Constraints and Generic Classes

A type variable can be restricted in two ways. A bound, written [T: Base], accepts Base and any of its subclasses; a set of constraints, written [T: (A, B)], accepts exactly one of the listed types and forbids mixing them. The same bracket syntax declares generic classes, and the statement type declares generic aliases.

def longest[S: (str, bytes)](a: S, b: S) -> S:
    return a if len(a) >= len(b) else b

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]

print(longest("python", "go"))                    # Output: python
print(longest.__type_params__[0].__constraints__) # Output: (<class 'str'>, <class 'bytes'>)

numbers = Stack[int]()
numbers.push(10)
print(numbers.pop())                              # Output: 10
print(Pair[float])                                # Output: Pair[float]

The constraint forbids a call such as longest("text", b"bytes"), which a type checker reports, because the two arguments would bind S to different types. The class Stack[int] lets the checker reject numbers.push("ten") and infer int for the result of pop. Python 3.13 added defaults for type parameters (PEP 696), so a declaration such as class Box[T = int] can omit the argument.

Protocols: Structural Typing

A protocol describes the methods an object must have, without requiring any inheritance, which is the static counterpart of duck typing. It was introduced in Python 3.8 (PEP 544) and is the natural type for interchangeable components, as shown in the article devoted to the Strategy pattern.

from collections.abc import Iterable
from typing import Protocol, runtime_checkable

@runtime_checkable
class Closeable(Protocol):
    def close(self) -> None: ...

class Connection:
    def close(self) -> None:
        print("connection closed")

class Report:
    pass

def shutdown(resources: Iterable[Closeable]) -> None:
    for resource in resources:
        resource.close()

shutdown([Connection()])                 # Output: connection closed
print(isinstance(Connection(), Closeable))  # Output: True
print(isinstance(Report(), Closeable))      # Output: False

The class Connection never mentions Closeable, yet it satisfies the protocol because it has a compatible close method. The decorator runtime_checkable additionally allows isinstance checks, but those checks are much weaker than the static ones, as the pitfalls section shows.

Callables and Decorators

The type of a function is written Callable[[arguments], result], and since Python 3.9 it is imported from collections.abc; typing.Callable survives only as a deprecated alias. This notation cannot describe keyword arguments, which is a problem for decorators: a decorator annotated with Callable[..., R] erases the signature of the function it wraps. ParamSpec, added in Python 3.10 (PEP 612) and written **P in the new syntax, captures the complete parameter list and transfers it to the wrapper.

import functools
from collections.abc import Callable

def logged[**P, R](func: Callable[P, R]) -> Callable[P, R]:
    @functools.wraps(func)
    def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
        print(f"calling {func.__name__}")
        return func(*args, **kwargs)
    return wrapper

@logged
def greet(name: str, excited: bool = False) -> str:
    return name + ("!" if excited else ".")

print(greet("Ada", excited=True))
# Output: calling greet
# Output: Ada!

With this annotation, a type checker knows that greet still takes a string and an optional boolean, and it reports a call such as greet(42) even though the call passes through the wrapper. The mechanism of the decorator itself is the one examined in the article devoted to decorators; ParamSpec only makes its typing exact.

Annotations at Runtime

The interpreter does not enforce annotations: they are metadata, stored on the function and read by type checkers, editors and some libraries. A function annotated with n: int accepts a string without complaint, and only a static checker such as mypy or pyright reports the mismatch before the program runs.

def double(n: int) -> int:
    return n * 2

print(double("ab"))           # Output: abab
print(double.__annotations__) # Output: {'n': <class 'int'>, 'return': <class 'int'>}

Some libraries do read annotations at runtime, for example dataclasses to discover fields and functools.singledispatch to choose implementations, as described in the article devoted to singledispatch. Python 3.14 changed when those annotations are evaluated (PEP 649 and PEP 749): they are no longer computed when the function or class is defined, but only when they are requested, so an annotation may refer to a class defined later in the module without quotes. The new module annotationlib lets tools request annotations as values, as forward references or as strings, and the directive from __future__ import annotations keeps its previous behaviour of storing them as strings.

Pitfalls of Advanced Type Hints

The typing system is expressive, but several of its constructs mean less, or something different, than they appear to. Five pitfalls are distinguished, which are the following:

  1. No runtime enforcement. Annotations document intent; without a type checker in the workflow, they detect nothing.
  2. Weak runtime protocol checks. isinstance with a runtime_checkable protocol verifies only that the methods exist, not their signatures.
  3. Over-narrow parameters. Annotating a parameter as list[T] rejects tuples and other sequences that the function handles correctly; abstract types such as Sequence or Iterable are usually more accurate.
  4. Erased signatures. A decorator typed with Callable[..., R] hides the parameters of the decorated function; ParamSpec preserves them.
  5. Overuse of Any. Any disables checking for everything it touches, and it spreads through every expression derived from it.

The second pitfall is reproduced in the following example.

from typing import Protocol, runtime_checkable

@runtime_checkable
class Closeable(Protocol):
    def close(self) -> None: ...

class Door:
    def close(self, force: bool) -> None:  # Requires an extra argument.
        print("door closed")

door = Door()
print(isinstance(door, Closeable))  # Output: True

try:
    door.close()
except TypeError as error:
    print(error)  # Output: Door.close() missing 1 required positional argument: 'force'

The runtime check accepts Door because it has a method named close, although that method cannot be called the way the protocol promises. A static checker would reject Door where a Closeable is expected; at runtime, the protocol only asserts the presence of a name.

Choosing the Right Construct

Consequently, each construct of this article answers a specific relationship between types, and the following table summarizes the correspondence.

Need Recommended construct
Output type equal to input type Type parameter: def f[T](x: T) -> T
Accept a type and its subclasses Bound: [T: Base]
Accept one of a closed set of types, without mixing Constraints: [T: (str, bytes)]
Container of any element type Generic class: class Stack[T]
Named reusable type, possibly generic type statement: type Pair[T] = tuple[T, T]
Accept objects by behaviour, not ancestry Protocol
Function arguments collections.abc.Callable[[A, B], R]
Decorators that keep the signature ParamSpec: def deco[**P, R](f: Callable[P, R]) -> Callable[P, R]
Code that must run before Python 3.12 TypeVar and ParamSpec declared at module level

Conclusion

It is concluded that advanced type hints describe relationships rather than single types: a type parameter ties the output of a function to its input, bounds and constraints limit what may be bound, protocols accept objects by their behaviour, and ParamSpec carries a complete signature through a decorator. The syntax of Python 3.12 made generic code nearly as short as ordinary code, and Python 3.14 deferred the evaluation of annotations, which removes most forward-reference problems. This magic, however, works only in combination with a type checker, since the interpreter itself ignores every annotation. Protocols and static duck typing, introduced briefly here, deserve a fuller treatment, which is developed in a future article of this series.