Sub topic 3
Generic Protocols and Advanced Type Parameters
Assume Python 3.12 or later, basic annotations such as list[int], and a checker such as mypy or pyright. These features mainly help the checker; Python usually does not enforce them while running.
Generic protocols
A protocol describes an interface by listing the methods an object must provide. A generic protocol uses a type parameter so the same interface works with different result types. This is structural typing: a class matches because it has the required methods, not because it inherits from the protocol.
from typing import Protocol
class Repository[T](Protocol):
def get(self, key: str) -> T: ...
class User:
def __init__(self, name: str) -> None:
self.name = name
class MemoryRepository:
def get(self, key: str) -> User:
return User(key)
def load_user(repo: Repository[User], key: str) -> User:
return repo.get(key)
user = load_user(MemoryRepository(), "Ada")MemoryRepository never names Repository, but it satisfies Repository[User].
ParamSpec: typing decorators
ParamSpec captures an entire callable signature. Use it when a decorator forwards positional and keyword arguments while preserving the decorated function's type.
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 f"Hello, {name}" + ("!" if excited else ".")Defaults and variadic type parameters
Python 3.13 supports defaults for type parameters. A checker can interpret bare Response as Response[str].
class Response[T = str]:
def __init__(self, body: T) -> None:
self.body = bodyTypeVarTuple represents an arbitrary number of type arguments. It is useful when a function preserves the exact types and order of its arguments.
def pack[*Ts](*items: *Ts) -> tuple[*Ts]:
return items
values = pack(1, "x", 2.5) # tuple[int, str, float]Scoping, evaluation, and runtime behavior
Type parameters belong to the function, class, or alias where they are declared. They do not become ordinary global variables. The type statement evaluates aliases lazily, which permits recursive aliases such as Json without defining every name first.
At runtime, Box[int] may retain metadata such as __origin__, but constructing Box[int]("text") does not automatically reject the string. Treat generic arguments as static contracts unless you add explicit runtime validation.
> callout note > A protocol checks behavior, while a generic parameter describes the type flowing through that behavior.
Exercise
Why can MemoryRepository be passed to load_user without inheriting from Repository?
Show answer
It structurally matches Repository[User] because it provides get(self, key: str) -> User.