Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

typing.ParamSpec

Capture a callable’s parameter list so a decorator can preserve positional and keyword call rules in static types.

Version: Python 3.14; repository image, production runtime not attested

Syntax

P = ParamSpec("P")

Capture a callable’s parameter list so a decorator can preserve positional and keyword call rules in static types.

P.args and P.kwargs annotate the wrapper’s variadic positional and keyword parameters together. The wrapper must still forward the actual arguments.

Its annotation does not prevent an invalid call from reaching the wrapped function and raising TypeError.

Examples

from collections.abc import Callable
from typing import ParamSpec, TypeVar
P = ParamSpec("P")
R = TypeVar("R")

def relay(f: Callable[P, R]) -> Callable[P, R]:
    def wrapped(*args: P.args, **kwargs: P.kwargs) -> R:
        return f(*args, **kwargs)
    return wrapped

@relay
def price(n: int, *, rate: int) -> int:
    return n * rate

print(price(3, rate=4))
try:
    price(3, 4)
except TypeError:
    print("keyword only")

Result

12
keyword only

Its annotation does not prevent an invalid call from reaching the wrapped function and raising TypeError.

Sources