Sub topic 13
Typing decorators with ParamSpec
This chapter assumes you can write a decorator with functools.wraps, including a decorator factory, and that you know basic type hints such as Callable. The examples need Python 3.10 or newer. On older versions, import ParamSpec and Concatenate from typing_extensions.
The problem: decorators erase signatures
A decorator replaces a function with its wrapper. A type checker such as mypy or pyright only sees what you declare about that wrapper. The simplest annotation throws the signature away:
import functools
from typing import Any, Callable
def logged(func: Callable[..., Any]) -> Callable[..., Any]:
@functools.wraps(func)
def wrapper(*args: Any, **kwargs: Any) -> Any:
print(f"calling {func.__name__}")
return func(*args, **kwargs)
return wrapper
@logged
def add(a: int, b: int) -> int:
return a + b
result = add("x", None) # the checker accepts this callAfter decoration, add has the type Callable[..., Any]. The checker no longer knows the parameters, and result has type Any. Wrong calls pass, and your editor loses autocomplete and argument hints.
ParamSpec captures the parameters
A ParamSpec is a type variable that stands for a whole parameter list. Pair it with a TypeVar for the return type:
import functools
from typing import Callable, ParamSpec, TypeVar
P = ParamSpec("P")
R = TypeVar("R")
def logged(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 add(a: int, b: int) -> int:
return a + b
print(add(2, 3)) # the checker knows this returns int
# add("x", 3) # the checker reports an errorThe signature Callable[P, R] says that the input and output functions share the same parameters P and return type R. Inside the wrapper, P.args types *args and P.kwargs types **kwargs. You must use them together, and only on those two parameters.
Changing the signature with Concatenate
Some decorators add or remove a parameter. Concatenate describes a parameter list with extra leading entries. This decorator supplies the first argument itself, so callers no longer pass it:
import functools
from typing import Callable, Concatenate, ParamSpec, TypeVar
P = ParamSpec("P")
R = TypeVar("R")
def with_prefix(func: Callable[Concatenate[str, P], R]) -> Callable[P, R]:
@functools.wraps(func)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
return func("[app]", *args, **kwargs)
return wrapper
@with_prefix
def log(prefix: str, message: str) -> None:
print(prefix, message)
log("started") # prints: [app] startedThe checker sees log as (message: str) -> None. A call such as log("[x]", "started") is an error.
Typing a decorator factory
A factory has one more layer, so the return annotation names the inner decorator. It takes a callable and returns a callable with the same signature:
import functools
from typing import Callable, ParamSpec, TypeVar
P = ParamSpec("P")
R = TypeVar("R")
def repeat(times: int) -> Callable[[Callable[P, R]], Callable[P, R]]:
def decorator(func: Callable[P, R]) -> Callable[P, R]:
@functools.wraps(func)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
result = func(*args, **kwargs)
for _ in range(times - 1):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@repeat(times=2)
def say(message: str) -> None:
print(message)
say("hello") # prints hello twiceCommon mistakes
- Using
P.argsoutside the wrapper's*args.P.argsandP.kwargsare only valid as the annotations of*argsand**kwargs, and they must appear as a pair. - Typing an async decorator like a sync one. For a decorated coroutine function, use
Callable[P, Awaitable[R]]for the input. The wrapper must beasync defand returnR. - Expecting runtime checks.
ParamSpecaffects only the static checker. Python does not validate arguments at run time because of it. - Typing class-based decorators. A class that implements
__call__needs its own generic typing.ParamSpecworks best with function decorators.
Exercise
A decorator is annotated def slow(func: Callable[..., Any]) -> Callable[..., Any]. What does a type checker lose when you decorate def area(w: float, h: float) -> float with it, and how do you fix the annotation?
Show answer
The checker treats area as Callable[..., Any]. It no longer knows the parameter types or the float return type, so wrong calls pass and the result is Any. Fix it with P = ParamSpec("P") and R = TypeVar("R"). Annotate the decorator as def slow(func: Callable[P, R]) -> Callable[P, R]. Annotate the wrapper as def wrapper(*args: P.args, **kwargs: P.kwargs) -> R.