Forward Parameter Lists with ParamSpec
Core idea
ParamSpec captures an entire callable parameter list for static checking, including keyword arguments. Callable[P, R] relates the original to the wrapper. Concatenate[Context, P] describes a callable with an extra leading positional argument. ParamSpec and Concatenate require Python 3.10+.
from typing import Callable, ParamSpec, TypeVarP=ParamSpec('P'); R=TypeVar('R')def trace(fn:Callable[P,R])->Callable[P,R]: def inner(*args:P.args, **kwargs:P.kwargs)->R: print('call') return fn(*args,**kwargs) return inner@tracedef quote(n:int, *, rate:int=2)->int: return n*rateprint(quote(3,rate=4))P relates forwarding arguments to the original signature; R relates the result.
Supply a leading context
from typing import Callable,Concatenate,ParamSpec,TypeVarP=ParamSpec('P'); R=TypeVar('R')def bind(fn:Callable[Concatenate[str,P],R])->Callable[P,R]: def inner(*args:P.args,**kwargs:P.kwargs)->R: return fn('west',*args,**kwargs) return inner@binddef code(region:str, /, n:int)->str: return f'{region}-{n}'print(code(5))The public call omits the injected positional context.
Common mistake
Callable[..., R] does not retain the exact parameters. Concatenate is not for injecting arbitrary keyword-only parameters.
Practice
Adapt the binder to inject a numeric prefix and check that callers supply only the remaining arguments.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
ParamSpec and Concatenate
Check your understanding of paramspec and concatenate.
What is printed?
from typing import ParamSpecP=ParamSpec('P')print(P.__name__)What is printed?
def bind(f): return lambda n: f(2,n)print(bind(lambda a,b:a*b)(5))What preserves a callable parameter list?
What does Concatenate model here?