Sub topic 13
Typing Decorators with ParamSpec
What this chapter assumes
You should already be able to write a decorator that forwards *args and **kwargs, use functools.wraps, and build a decorator factory. You should also know basic type hints such as int, list[str], and Callable[[int], str]. This chapter adds one thing: type annotations that let a type checker (mypy, pyright) see through a decorator.
The examples need Python 3.10 or later. On older versions, import ParamSpec and Concatenate from typing_extensions.
The problem: decorators erase signatures
Here is a decorator with no annotations.
import functools
def logged(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(f"calling {func.__name__}")
return func(*args, **kwargs)
return wrapper
@logged
def add(a: int, b: int) -> int:
return a + bAt runtime this works. A type checker sees something different. logged has no annotations, so the checker treats add as having an unknown type. Calls such as add("x") or add(1, 2, 3) go unreported, and the result of add(1, 2) is not known to be an int. Your editor also stops offering parameter hints for add.
A first attempt is to annotate the decorator with Callable[..., Any]. That makes the checker accept the decorator, but it still discards the parameters and the return type.
Capturing the return type with TypeVar
A TypeVar is a placeholder for a type that the checker fills in at each use. It can carry the return type through the decorator:
from typing import Any, Callable, TypeVar
R = TypeVar("R")
def logged(func: Callable[..., R]) -> Callable[..., R]:
...The return type now survives, so add(1, 2) is known to be an int. The parameters are still ..., which means "anything". A TypeVar stands for a single type, and a parameter list is not a single type. This is the gap that ParamSpec fills.
ParamSpec captures a whole parameter list
A ParamSpec is a placeholder for an entire parameter list: the names, types, defaults, and the positional or keyword kind of each parameter. You use it in two places.
- Inside
Callable[P, R], to say "a callable with parametersPthat returnsR". - In the wrapper's signature, as
*args: P.argsand**kwargs: P.kwargs, to say "this wrapper takes exactly the parameters thatPcaptured".
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)) # prints "calling add", then 5When the checker sees @logged on add, it solves Callable[P, R] against add's type. It sets P to (a: int, b: int) and R to int. The decorated add therefore has the type Callable[(a: int, b: int), int], the same as before. A call like add("x", 2) is now an error, and add(1, b=2) is accepted.
The rules for P.args and P.kwargs
P.args and P.kwargs are only valid as the annotations for *args and **kwargs, and they must appear together. The checker enforces this pairing.
- You cannot annotate
*args: P.argswithout**kwargs: P.kwargs. - You cannot use
P.argsas the type of an ordinary variable or parameter. - When you call the wrapped function, you must pass both
*argsand**kwargs. Passing only one is an error.
Decorator factories
A factory adds one more level of nesting, so it needs one more level of annotation. The factory returns a decorator, and that decorator has the type Callable[[Callable[P, R]], Callable[P, R]].
import functools
from typing import Callable, ParamSpec, TypeVar
P = ParamSpec("P")
R = TypeVar("R")
def retry(times: int) -> Callable[[Callable[P, R]], Callable[P, R]]:
if times < 1:
raise ValueError("times must be at least 1")
def decorator(func: Callable[P, R]) -> Callable[P, R]:
@functools.wraps(func)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
last_error: Exception | None = None
for _ in range(times):
try:
return func(*args, **kwargs)
except Exception as exc:
last_error = exc
assert last_error is not None
raise last_error
return wrapper
return decorator
attempts = 0
@retry(times=3)
def flaky(threshold: int) -> str:
global attempts
attempts += 1
if attempts < threshold:
raise RuntimeError("not yet")
return f"ok after {attempts} attempts"
print(flaky(3)) # ok after 3 attemptsP and R are not bound when the checker reads retry(times=3). They are bound later, when the returned decorator is applied to flaky. This is why the return annotation spells out a generic callable instead of naming specific types.
Async functions
An async def function returns a coroutine when called. To keep the typing honest, make the wrapper async and describe the decorated function as returning Coroutine[Any, Any, R].
import asyncio
import functools
from typing import Any, Callable, Coroutine, ParamSpec, TypeVar
P = ParamSpec("P")
R = TypeVar("R")
def log_calls(
func: Callable[P, Coroutine[Any, Any, R]],
) -> Callable[P, Coroutine[Any, Any, R]]:
@functools.wraps(func)
async def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
print(f"calling {func.__name__}")
return await func(*args, **kwargs)
return wrapper
@log_calls
async def fetch(value: int) -> int:
await asyncio.sleep(0.01)
return value
print(asyncio.run(fetch(42))) # calling fetch, then 42Here R is the value you get after await, not the coroutine itself. A sync decorator typed as Callable[P, R] would see R as a coroutine object and would not match this shape.
Changing the signature with Concatenate
Some decorators add or remove a parameter. A common case is a decorator that supplies the first argument. Concatenate prepends fixed parameter types to a ParamSpec.
import functools
from typing import Callable, Concatenate, ParamSpec, TypeVar
P = ParamSpec("P")
R = TypeVar("R")
class Connection:
def close(self) -> None:
print("closed")
def with_connection(
func: Callable[Concatenate[Connection, P], R],
) -> Callable[P, R]:
@functools.wraps(func)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
conn = Connection()
try:
return func(conn, *args, **kwargs)
finally:
conn.close()
return wrapper
@with_connection
def count_rows(conn: Connection, table: str) -> int:
return 3
print(count_rows("users")) # closed, then 3The input type says the first parameter is a Connection and the rest are P. The output type is Callable[P, R], so callers do not pass the connection. Calling count_rows(Connection(), "users") is a type error.
Which tool to use
| Situation | Use |
|---|---|
| The decorator only needs the return type | `Callable[..., R]` with a `TypeVar` |
| The wrapper keeps the same parameters | `ParamSpec` with `Callable[P, R]` |
| The decorator adds a leading parameter to the call | `Concatenate[X, P]` on the input |
| The decorator removes a leading parameter | `Concatenate[X, P]` in the input, `P` in the output |
| The decorator changes the parameters in other ways | Return a specific `Callable[[...], R]` and accept the loss of generality |
Checking what the checker sees
Run your checker on a small test file and ask it to reveal the type. In mypy and pyright, reveal_type(add) prints the inferred type during checking. The call is only for the checker. It exists at runtime from Python 3.11 in typing, so remove it or guard it with TYPE_CHECKING before you ship.
from typing import TYPE_CHECKING
if TYPE_CHECKING:
reveal_type(add) # the checker prints the decorated typeAdd a few deliberately wrong calls in a test file, such as add("x", 2), and confirm that the checker reports each one. A typed decorator that accepts bad calls has lost the signature somewhere.
Common errors
- A missing
ParamSpecpair. Writing*args: P.argswithout**kwargs: P.kwargsfails type checking. - Using
Callable[..., R]and expecting parameter checking. The...form accepts any arguments, so nothing is checked. - Annotating the wrapper as returning
Any. The decorated function then returnsAny. Annotate the wrapper with-> R. - Using a sync signature for an async function.
Callable[P, R]bindsRto a coroutine. Use theCoroutine[Any, Any, R]form for async functions. - Forgetting that class-based decorators need their own typing. A decorator class like
CountCallshas instance attributes and__call__. To keep the signature, make the class generic overPandR(Generic[P, R]) and type__call__withP.argsandP.kwargs. - Expecting
functools.wrapsto fix typing. It copies runtime metadata such as__name__and__doc__. The checker still needs the annotations above.
Exercises
Exercise
A decorator is annotated def deco(func: Callable[..., R]) -> Callable[..., R]. After decoration, a function def f(x: int) -> str is called as f("a", "b"). Does the type checker report an error? What does the checker still know about the result?
Show answer
No error. The ... accepts any arguments, so the parameter check is lost. The checker still knows the result is a str, because R carries the return type.
Exercise
Write the type annotations (the function signature only) for a decorator timed that wraps any synchronous function and keeps its exact parameters and return type.
Show answer
def timed(func: Callable[P, R]) -> Callable[P, R], with P = ParamSpec("P") and R = TypeVar("R"). The inner wrapper is declared as def wrapper(args: P.args, *kwargs: P.kwargs) -> R.
Exercise
A decorator inject_user calls the wrapped function as func(current_user(), *args, **kwargs). The wrapped functions take a User as their first parameter. Which typing construct describes the input function, and what is the return type of the decorator?
Show answer
The input is Callable[Concatenate[User, P], R]. The return type is Callable[P, R], because callers no longer pass the user.
Exercise
Why does an async decorator typed as Callable[P, R] -> Callable[P, R] give the wrong result type for async def fetch() -> int?
Show answer
For an async function, the callable returns a coroutine, so R is bound to Coroutine[Any, Any, int] instead of int. The wrapper's await then produces a different type from the one the annotation claims. Use Callable[P, Coroutine[Any, Any, R]] and make the wrapper async def returning R.