How do you correctly type-hint a function using *args and **kwargs with modern typing, like ParamSpec for preserving a wrapped function's exact signature?
Short answer
typing.ParamSpec (Python 3.10+) lets you capture an ENTIRE parameter signature (both positional and keyword parts) as a single type variable, letting a generic decorator's type hints correctly preserve the WRAPPED function's exact original signature — something plain *args: Any…
Advertisement
AModel answer
typing.ParamSpec (Python 3.10+) lets you capture an ENTIRE parameter signature (both positional and keyword parts) as a single type variable, letting a generic decorator's type hints correctly preserve the WRAPPED function's exact original signature — something plain *args: Any, **kwargs: Any annotations can't express.
from typing import ParamSpec, TypeVar, Callable
P = ParamSpec("P")
R = TypeVar("R")
def logged(func: Callable[P, R]) -> Callable[P, R]:
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
print(f"Calling {func.__name__}")
return func(*args, **kwargs)
return wrapperReal-world example
Writing a fully type-safe generic decorator whose type checker output correctly reflects the wrapped function's exact original parameter types.
Likely follow-ups
- How does a type checker like mypy actually USE ParamSpec to verify calls to the wrapped, decorated function?
Related topics