ParamSpec Preserves Decorator Signatures
Type a decorator with ParamSpec so the wrapped function keeps its exact parameters and return type for callers and type checkers alike.
Code
import functools
from typing import Callable, ParamSpec, TypeVar
P = ParamSpec('P')
R = TypeVar('R')
def logged(fn: Callable[P, R]) -> Callable[P, R]:
@functools.wraps(fn)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
print('calling', fn.__name__, 'with', len(args), 'positional args')
result = fn(*args, **kwargs)
print(fn.__name__, 'returned', repr(result))
return result
return wrapper
@logged
def total(items: list[int], tax: float = 0.0) -> float:
return sum(items) * (1 + tax)
print(total([10, 20], tax=0.1))Output
Captured from a sandboxed run of this snippet in the build pipeline.
calling total with 1 positional args
total returned 33.0
33.0Inside the snippet
ParamSpec Preserves Decorator Signatures keeps everything in the functions logged, wrapper and total.
Using it
Entry signature: def logged(fn: Callable[P, R]) -> Callable[P, R]
Running the file prints labeled results such as calling — each operation’s effect is visible in the output.
logged is the public entry point; everything else in the file exists to support it.
Key statements
def total(items: list[int], tax: float = 0.0) -> float:
return sum(items) * (1 + tax)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
print('calling', fn.__name__, 'with', len(args), 'positional args')
result = fn(*args, **kwargs)
print(fn.__name__, 'returned', repr(result))
return result
Interactive Tools for This Topic
FAQ
- Do I need to install anything before running this?
- No — every API used here ships with the language runtime, so there is nothing to install. Every import resolves inside the standard library — `functools`, `typing`. The file defines `logged`, `wrapper`, `total` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.