Typing decorators with ParamSpec and Concatenate

suggest change

A decorator replaces a function with another function. Unless the decorator is annotated carefully, a type checker loses the original signature: every call to the decorated function is accepted, and the return type becomes Any.

typing.ParamSpec (Python 3.10, PEP 612) fixes that. It is a type variable that stands for a whole parameter list, so a decorator can say "I return a function that takes the same arguments as the one I was given". Its companion typing.Concatenate describes a parameter list with extra positional parameters added in front, which is how you type decorators that inject or add an argument. Python 3.12 (PEP 695) added a shorter spelling: def deco[**P, R](...).

Examples were run with Python 3.13.15. Type checker output is from mypy 2.4.0 and pyright 1.1.414, with absolute paths shortened to the file name.

How decorators work at runtime is covered in Decorator function, Decorator with arguments decorator factory and Making a decorator look like the decorated function (functools.wraps). The [T] syntax for type parameters is explained in Generics with type parameter syntax (PEP 695).

The problem: Callable[..., Any] erases the signature

The obvious way to annotate a decorator is with Callable[..., Any], "a callable taking any arguments":

from collections.abc import Callable
from typing import Any
import functools

def logged(func: Callable[..., Any]) -> Callable[..., Any]:
    @functools.wraps(func)
    def wrapper(*args: Any, **kwargs: Any) -> Any:
        print(f"calling {func.__name__}{args}")
        return func(*args, **kwargs)
    return wrapper

@logged
def add(a: int, b: int) -> int:
    return a + b

print(add(2, 3))
total: str = add(2, 3)
add("two", 3, verbose=True)
calling add(2, 3)
5
calling add(2, 3)
calling add('two', 3)
Traceback (most recent call last):
  ...
TypeError: add() got an unexpected keyword argument 'verbose'

Both checkers are happy with this file, even though add returns int, not str, and the last call crashes:

$ mypy s1.py
Success: no issues found in 1 source file

$ pyright s1.py
0 errors, 0 warnings, 0 informations

The decorator told the checker that add is now "any callable returning anything", so the checker has nothing to check. Using a TypeVar for the return type (Callable[..., R]) keeps the return type but still accepts any arguments. Before Python 3.10 there was no way to say "the same parameters as the input".

ParamSpec: forwarding the parameter list

A ParamSpec captures all parameters of a callable: their names, types, defaults, and whether they are positional or keyword. Inside the wrapper, P.args and P.kwargs give the types of *args and **kwargs:

from collections.abc import Callable
from typing import ParamSpec, TypeVar, reveal_type
import functools

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__} args={args} kwargs={kwargs}")
        return func(*args, **kwargs)
    return wrapper

@logged
def add(a: int, b: int = 0) -> int:
    return a + b

reveal_type(add)
print(add(2, b=3))
total: str = add(2, 3)
add("two", 3, verbose=True)
Runtime type is 'function'
calling add args=(2,) kwargs={'b': 3}
5
calling add args=(2, 3) kwargs={}
calling add args=('two', 3) kwargs={'verbose': True}
Traceback (most recent call last):
  ...
TypeError: add() got an unexpected keyword argument 'verbose'

Now the checkers see the real signature of add and report both mistakes:

$ mypy s2.py
s2.py:19: note: Revealed type is "def (a: int, b: int =) -> int"
s2.py:21: error: Incompatible types in assignment (expression has type "int", variable has type "str")  [assignment]
s2.py:22: error: Unexpected keyword argument "verbose" for "add"  [call-arg]
s2.py:22: error: Argument 1 to "add" has incompatible type "str"; expected "int"  [arg-type]
Found 3 errors in 1 file (checked 1 source file)

$ pyright s2.py
  s2.py:19:13 - information: Type of "add" is "(a: int, b: int = 0) -> int"
  s2.py:21:14 - error: Type "int" is not assignable to declared type "str"
    "int" is not assignable to "str" (reportAssignmentType)
  s2.py:22:15 - error: No parameter named "verbose" (reportCallIssue)
2 errors, 0 warnings, 1 information

The parameter names and defaults survive too, so add(2, b=3) is checked and IDEs show (a: int, b: int = 0) in tooltips.

How it works:

ParamSpec and Concatenate are in typing since Python 3.10. For 3.8 and 3.9 import them from the typing_extensions package.

The PEP 695 syntax: def deco[**P, R]

Since Python 3.12 you can declare type parameters in brackets after the function name. A ParamSpec is written with two stars, a TypeVar with none (and a TypeVarTuple with one star, see below). No module-level P = ParamSpec("P") is needed and the names are scoped to the function.

The rest of this article uses this syntax. Here it is in a decorator factory, a function that takes options and returns the actual decorator:

from collections.abc import Callable
import functools
import time

def retry[**P, R](
    times: int = 3, delay: float = 0.0
) -> Callable[[Callable[P, R]], Callable[P, R]]:
    def decorator(func: Callable[P, R]) -> Callable[P, R]:
        @functools.wraps(func)
        def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
            for attempt in range(1, times + 1):
                try:
                    return func(*args, **kwargs)
                except ConnectionError as e:
                    print(f"attempt {attempt} failed: {e}")
                    if attempt == times:
                        raise
                    time.sleep(delay)
            raise AssertionError("unreachable")
        return wrapper
    return decorator

calls = 0

@retry(times=3)
def fetch(url: str, *, timeout: float = 1.0) -> bytes:
    global calls
    calls += 1
    if calls < 3:
        raise ConnectionError("network down")
    return b"ok from " + url.encode()

print(fetch("example.com", timeout=2.5))
fetch("example.com", 2.5)
attempt 1 failed: network down
attempt 2 failed: network down
b'ok from example.com'
Traceback (most recent call last):
  ...
TypeError: fetch() takes 1 positional argument but 2 were given

timeout is keyword-only in fetch, and the checkers know that through the decorator:

$ mypy s3.py
s3.py:34: error: Too many positional arguments for "fetch"  [call-arg]
Found 1 error in 1 file (checked 1 source file)

$ pyright s3.py
  s3.py:34:22 - error: Expected 1 positional argument (reportCallIssue)
1 error, 0 warnings, 0 informations

P and R are declared on retry even though they only appear in its return type. That's the usual way to annotate a factory: the checker solves P and R later, when the returned decorator is applied to fetch.

Always annotate the decorator's return type

functools.wraps is itself typed in typeshed, and pyright can infer a useful type from it. mypy doesn't infer return types of functions at all, so an unannotated decorator turns every decorated function into Any:

from collections.abc import Callable
from typing import reveal_type
import functools

def logged[**P, R](func: Callable[P, R]):
    @functools.wraps(func)
    def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
        return func(*args, **kwargs)
    return wrapper

@logged
def add(a: int, b: int) -> int:
    return a + b

reveal_type(add)
add("x", 1)
$ mypy s13.py
s13.py:15: note: Revealed type is "Any"
Success: no issues found in 1 source file

$ pyright s13.py
  s13.py:15:13 - information: Type of "add" is "_Wrapped[(a: int, b: int), int, (a: int, b: int), int]"
  s13.py:16:5 - error: Argument of type "Literal['x']" cannot be assigned to parameter "a" of type "int" in function "__call__"
    "Literal['x']" is not assignable to "int" (reportArgumentType)
1 error, 0 warnings, 1 information

Even with pyright the explicit -> Callable[P, R] gives a cleaner type than the private _Wrapped class. Write it out.

Changing the return type

P and R are independent, so a decorator can keep the parameters and change the result. Here timed returns the result together with the elapsed time, and in_thread turns a blocking function into an async one that runs in a worker thread:

from collections.abc import Callable, Coroutine
from typing import Any, reveal_type
import asyncio
import functools
import time

def timed[**P, R](func: Callable[P, R]) -> Callable[P, tuple[R, float]]:
    @functools.wraps(func)
    def wrapper(*args: P.args, **kwargs: P.kwargs) -> tuple[R, float]:
        start = time.perf_counter()
        result = func(*args, **kwargs)
        return result, time.perf_counter() - start
    return wrapper

def in_thread[**P, R](
    func: Callable[P, R],
) -> Callable[P, Coroutine[Any, Any, R]]:
    @functools.wraps(func)
    async def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
        return await asyncio.to_thread(func, *args, **kwargs)
    return wrapper

@timed
def slow_square(x: int) -> int:
    time.sleep(0.05)
    return x * x

@in_thread
def read_size(path: str, encoding: str = "utf-8") -> int:
    with open(path, encoding=encoding) as f:
        return len(f.read())

value, seconds = slow_square(7)
print(value, seconds > 0.04)
reveal_type(slow_square)
reveal_type(read_size)

async def main() -> None:
    n = await read_size(__file__)
    print(n > 0)

asyncio.run(main())
49 True
Runtime type is 'function'
Runtime type is 'function'
True
$ mypy s4.py
s4.py:35: note: Revealed type is "def (x: int) -> tuple[int, float]"
s4.py:36: note: Revealed type is "def (path: str, encoding: str =) -> typing.Coroutine[Any, Any, int]"
Success: no issues found in 1 source file

$ pyright s4.py
  s4.py:35:13 - information: Type of "slow_square" is "(x: int) -> tuple[int, float]"
  s4.py:36:13 - information: Type of "read_size" is "(path: str, encoding: str = "utf-8") -> Coroutine[Any, Any, int]"
0 errors, 0 warnings, 2 informations

An async def function returns a coroutine, so the type of in_thread's result is Callable[P, Coroutine[Any, Any, R]]. Callable[P, Awaitable[R]] works too if callers only need to await it.

Concatenate: removing a leading argument

Many decorators supply an argument themselves: a database connection, a session, a logger, the current user. The decorated function declares that parameter first, but its callers must not pass it.

Concatenate[X, P] means "a parameter list that starts with a positional parameter of type X, followed by the parameters in P". Accept Callable[Concatenate[X, P], R] and return Callable[P, R], and the first parameter disappears from the outside:

from collections.abc import Callable
from typing import Concatenate, reveal_type
import functools
import sqlite3

DB_PATH = ":memory:"

def with_connection[**P, R](
    func: Callable[Concatenate[sqlite3.Connection, P], R],
) -> Callable[P, R]:
    @functools.wraps(func)
    def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
        conn = sqlite3.connect(DB_PATH)
        try:
            return func(conn, *args, **kwargs)
        finally:
            conn.close()
    return wrapper

@with_connection
def square_in_sql(conn: sqlite3.Connection, x: int) -> int:
    (result,) = conn.execute("SELECT ? * ?", (x, x)).fetchone()
    return result

reveal_type(square_in_sql)
print(square_in_sql(12))

@with_connection
def no_conn(x: int) -> int:
    return x

square_in_sql(sqlite3.connect(DB_PATH), 12)
Runtime type is 'function'
144
Traceback (most recent call last):
  ...
TypeError: square_in_sql() takes 2 positional arguments but 3 were given
$ mypy s5.py
s5.py:25: note: Revealed type is "def (x: int) -> int"
s5.py:28: error: Argument 1 to "with_connection" has incompatible type "Callable[[int], int]"; expected "Callable[[Connection], int]"  [arg-type]
s5.py:28: note: This is likely because "no_conn" has named arguments: "x". Consider marking them positional-only
s5.py:32: error: Too many arguments for "square_in_sql"  [call-arg]
s5.py:32: error: Argument 1 to "square_in_sql" has incompatible type "Connection"; expected "int"  [arg-type]
Found 3 errors in 1 file (checked 1 source file)

$ pyright s5.py
  s5.py:25:13 - information: Type of "square_in_sql" is "(x: int) -> int"
  s5.py:28:2 - error: Argument of type "(x: int) -> int" cannot be assigned to parameter "func" of type "(Connection, **P@with_connection) -> R@with_connection" in function "with_connection"
    Type "(x: int) -> int" is not assignable to type "(Connection, **P@with_connection) -> R@with_connection"
      Parameter 1: type "Connection" is incompatible with type "int"
        "Connection" is not assignable to "int" (reportArgumentType)
  s5.py:32:41 - error: Expected 1 positional argument (reportCallIssue)
2 errors, 0 warnings, 1 information

The checker verifies both sides:

Concatenate can prepend several parameters (Concatenate[Request, User, P]), but only positional ones, and the last argument must be a ParamSpec or .... Callable[Concatenate[int, ...], R] means "takes an int first, then anything".

Concatenate: adding a leading argument

Put Concatenate in the return type instead, and the decorator adds a parameter that callers must pass. This traced decorator requires a trace id as the new first argument:

from collections.abc import Callable
from typing import Concatenate, reveal_type
import functools

def traced[**P, R](func: Callable[P, R]) -> Callable[Concatenate[str, P], R]:
    @functools.wraps(func)
    def wrapper(trace_id: str, /, *args: P.args, **kwargs: P.kwargs) -> R:
        print(f"[{trace_id}] {func.__name__} start")
        result = func(*args, **kwargs)
        print(f"[{trace_id}] {func.__name__} -> {result!r}")
        return result
    return wrapper

@traced
def greet(name: str, punctuation: str = "!") -> str:
    return f"Hello, {name}{punctuation}"

reveal_type(greet)
greet("req-42", "Ada", punctuation="?")
greet("Ada")
Runtime type is 'function'
[req-42] greet start
[req-42] greet -> 'Hello, Ada?'
[Ada] greet start
Traceback (most recent call last):
  ...
TypeError: greet() missing 1 required positional argument: 'name'
$ mypy s6.py
s6.py:18: note: Revealed type is "def (str, name: str, punctuation: str =) -> str"
s6.py:20: error: Missing positional argument "name" in call to "greet"  [call-arg]
Found 1 error in 1 file (checked 1 source file)

$ pyright s6.py
  s6.py:18:13 - information: Type of "greet" is "(str, name: str, punctuation: str = "!") -> str"
  s6.py:20:1 - error: Argument missing for parameter "name" (reportCallIssue)
1 error, 0 warnings, 1 information

The added parameter has no name in the revealed type ((str, name: str, ...)): parameters added with Concatenate are positional-only. That's why the wrapper declares trace_id before /. Without the slash the wrapper would also accept trace_id=... as a keyword, and that could clash with a parameter of the same name in P.

Rules for P.args and P.kwargs

P.args and P.kwargs only make sense as a pair, as the types of *args and **kwargs of the same function. Using one without the other, or putting a keyword parameter between them, is an error:

from collections.abc import Callable

def only_args[**P, R](func: Callable[P, R]) -> Callable[P, R]:
    def wrapper(*args: P.args) -> R:
        return func(*args)
    return wrapper

def kw_in_between[**P, R](func: Callable[P, R]) -> Callable[P, R]:
    def wrapper(*args: P.args, verbose: bool = False, **kwargs: P.kwargs) -> R:
        return func(*args, **kwargs)
    return wrapper
$ mypy s7.py
s7.py:4: error: ParamSpec must have "*args" typed as "P.args" and "**kwargs" typed as "P.kwargs"  [valid-type]
s7.py:5: error: Too few arguments  [call-arg]
s7.py:6: error: Incompatible return value type (got "def wrapper(*args: Any) -> R", expected "Callable[P, R]")  [return-value]
s7.py:9: error: Arguments not allowed after ParamSpec.args  [valid-type]
s7.py:11: error: Incompatible return value type (got "def wrapper(*args: Any, verbose: bool = ..., **kwargs: Any) -> R", expected "Callable[P, R]")  [return-value]
Found 5 errors in 1 file (checked 1 source file)

$ pyright s7.py
  s7.py:4:24 - error: "args" and "kwargs" attributes of ParamSpec must both appear within a function signature (reportGeneralTypeIssues)
  s7.py:5:16 - error: Arguments for ParamSpec "P@only_args" are missing (reportCallIssue)
  s7.py:6:12 - error: Type "(*args: P@only_args.args) -> R@only_args" is not assignable to return type "(**P@only_args) -> R@only_args"
    Type "(*args: P@only_args.args) -> R@only_args" is not assignable to type "(**P@only_args) -> R@only_args" (reportReturnType)
  s7.py:9:32 - error: Keyword parameter "verbose" cannot appear in signature after ParamSpec args parameter (reportGeneralTypeIssues)
  s7.py:11:12 - error: Type "(*args: P@kw_in_between.args, verbose: bool = False, **kwargs: P@kw_in_between.kwargs) -> R@kw_in_between" is not assignable to return type "(**P@kw_in_between) -> R@kw_in_between"
    Type "(*args: P@kw_in_between.args, verbose: bool = False, **kwargs: P@kw_in_between.kwargs) -> R@kw_in_between" is not assignable to type "(**P@kw_in_between) -> R@kw_in_between" (reportReturnType)
5 errors, 0 warnings, 0 informations

So a decorator can't add a keyword-only parameter like verbose=True to an arbitrary function's signature. You can add positional parameters in front with Concatenate, or make the option a parameter of a decorator factory, as retry(times=3) does above.

Decorating methods

A method is a function whose first parameter is self, so a plain Callable[P, R] decorator works on methods unchanged: self becomes part of P, and binding to an instance removes it as usual.

When the decorator needs to use self, split it off with Concatenate and give it a bounded type parameter. This synchronized decorator works on any class whose instances have a _lock attribute, described by a Protocol:

from collections.abc import Callable
from typing import Concatenate, Protocol, reveal_type
import functools
import threading

class HasLock(Protocol):
    _lock: threading.Lock

def synchronized[S: HasLock, **P, R](
    method: Callable[Concatenate[S, P], R],
) -> Callable[Concatenate[S, P], R]:
    @functools.wraps(method)
    def wrapper(self: S, *args: P.args, **kwargs: P.kwargs) -> R:
        with self._lock:
            return method(self, *args, **kwargs)
    return wrapper

class Counter:
    def __init__(self) -> None:
        self._lock = threading.Lock()
        self.value = 0

    @synchronized
    def add(self, n: int = 1) -> int:
        self.value += n
        return self.value

class NoLock:
    @synchronized
    def run(self) -> None:
        pass

c = Counter()
threads = [threading.Thread(target=c.add, args=(2,)) for _ in range(100)]
for t in threads:
    t.start()
for t in threads:
    t.join()
print(c.value)
reveal_type(c.add)
reveal_type(Counter.add)
c.add("3")
200
Runtime type is 'method'
Runtime type is 'function'
Traceback (most recent call last):
  ...
TypeError: unsupported operand type(s) for +=: 'int' and 'str'
$ mypy s8.py
s8.py:29: error: Value of type variable "S" of "synchronized" cannot be "NoLock"  [type-var]
s8.py:40: note: Revealed type is "def (n: int =) -> int"
s8.py:41: note: Revealed type is "def (s8.Counter, n: int =) -> int"
s8.py:42: error: Argument 1 to "add" of "Counter" has incompatible type "str"; expected "int"  [arg-type]
Found 2 errors in 1 file (checked 1 source file)

$ pyright s8.py
  s8.py:29:6 - error: Argument of type "(self: Self@NoLock) -> None" cannot be assigned to parameter "method" of type "(S@synchronized, **P@synchronized) -> R@synchronized" in function "synchronized"
    Type "(self: Self@NoLock) -> None" is not assignable to type "(S@synchronized, **P@synchronized) -> R@synchronized"
      Parameter 1: type "S@synchronized" is incompatible with type "Self@NoLock"
        "HasLock*" is not assignable to "NoLock" (reportArgumentType)
  s8.py:40:13 - information: Type of "c.add" is "(n: int = 1) -> int"
  s8.py:41:13 - information: Type of "Counter.add" is "(Counter, n: int = 1) -> int"
  s8.py:42:7 - error: Argument of type "Literal['3']" cannot be assigned to parameter "n" of type "int"
    "Literal['3']" is not assignable to "int" (reportArgumentType)
2 errors, 0 warnings, 2 informations

S keeps the concrete class (Counter), so Counter.add still shows Counter as its first parameter and the bound c.add drops it. Using the protocol directly instead of S would also work, but the unbound method would then accept any object with a lock.

Class-based decorators

A decorator written as a class is generic over P and R, and its __call__ uses P.args and P.kwargs:

from collections.abc import Callable
from typing import reveal_type
import functools

class CountCalls[**P, R]:
    def __init__(self, func: Callable[P, R]) -> None:
        functools.update_wrapper(self, func)
        self.func = func
        self.calls = 0

    def __call__(self, *args: P.args, **kwargs: P.kwargs) -> R:
        self.calls += 1
        return self.func(*args, **kwargs)

@CountCalls
def power(base: float, exp: int = 2) -> float:
    return base**exp

print(power(3), power(2, exp=10), power.calls)
print(power.__name__)
reveal_type(power)
power(2, exp=0.5)
9 1024 2
power
Runtime type is 'CountCalls'
$ mypy s9.py
s9.py:20: error: "CountCalls[[float, int], float]" has no attribute "__name__"  [attr-defined]
s9.py:21: note: Revealed type is "s9.CountCalls[[base: float, exp: int =], float]"
s9.py:22: error: Argument "exp" to "__call__" of "CountCalls" has incompatible type "float"; expected "int"  [arg-type]
Found 2 errors in 1 file (checked 1 source file)

$ pyright s9.py
  s9.py:20:13 - error: Cannot access attribute "__name__" for class "CountCalls[(base: float, exp: int = 2), float]"
    Attribute "__name__" is unknown (reportAttributeAccessIssue)
  s9.py:21:13 - information: Type of "power" is "CountCalls[(base: float, exp: int = 2), float]"
  s9.py:22:14 - error: Argument of type "float" cannot be assigned to parameter "exp" of type "int" in function "__call__"
    "float" is not assignable to "int" (reportArgumentType)
2 errors, 0 warnings, 1 information

Calls are checked, and the extra calls attribute is typed, which a function-based decorator can't offer without a protocol. Two things to keep in mind:

ParamSpec at runtime

Type parameters are real objects at runtime. With the PEP 695 syntax they are stored in the function's __type_params__. inspect.signature follows the __wrapped__ attribute set by functools.wraps, which is how help() and IDEs show the original signature at runtime:

from collections.abc import Callable
from typing import get_type_hints
import functools
import inspect

def logged[**P, R](func: Callable[P, R]) -> Callable[P, R]:
    @functools.wraps(func)
    def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
        return func(*args, **kwargs)
    return wrapper

P, R = logged.__type_params__
print(logged.__type_params__)
print(type(P).__name__, P.__name__, P.args, P.kwargs)
print(get_type_hints(logged))

@logged
def add(a: int, b: int = 0) -> int:
    return a + b

print(inspect.signature(add))
print(inspect.signature(add, follow_wrapped=False))
(P, R)
ParamSpec P P.args P.kwargs
{'func': collections.abc.Callable[P, R], 'return': collections.abc.Callable[P, R]}
(a: int, b: int = 0) -> int
(*args, **kwargs) -> int

So ParamSpec handles static checking, functools.wraps handles runtime introspection, and a well-behaved decorator uses both.

TypeVarTuple for variadic positional arguments

ParamSpec captures a complete parameter list including keyword arguments. Sometimes you need something narrower: a sequence of positional types of any length. That's TypeVarTuple (Python 3.11, PEP 646), written *Ts in the PEP 695 syntax. It's the right tool for APIs like loop.call_soon(callback, *args) or threading.Thread(target, args), which pass loose positional arguments to a callback:

from collections.abc import Callable
from typing import reveal_type

def call_later[*Ts](callback: Callable[[*Ts], None], *args: *Ts) -> None:
    print("scheduled", callback.__name__, args)
    callback(*args)

def move(x: int, y: int, label: str) -> None:
    print(f"move {label} to ({x}, {y})")

call_later(move, 10, 20, "player")

def with_index[T, *Ts](index: T, row: tuple[*Ts]) -> tuple[T, *Ts]:
    return (index, *row)

r = with_index(1, ("Ada", 36, True))
reveal_type(r)
print(r)
call_later(move, 10, "player")
scheduled move (10, 20, 'player')
move player to (10, 20)
Runtime type is 'tuple'
(1, 'Ada', 36, True)
scheduled move (10, 'player')
Traceback (most recent call last):
  ...
TypeError: move() missing 1 required positional argument: 'label'
$ mypy s10.py
s10.py:17: note: Revealed type is "tuple[int, str, int, bool]"
s10.py:19: error: Argument 1 to "call_later" has incompatible type "Callable[[int, int, str], None]"; expected "Callable[[int, str], None]"  [arg-type]
Found 1 error in 1 file (checked 1 source file)

$ pyright s10.py
  s10.py:17:13 - information: Type of "r" is "tuple[int, str, int, bool]"
  s10.py:19:1 - error: Argument of type "tuple[Literal[10], Literal['player']]" cannot be assigned to parameter "args" of type "Ts@call_later" in function "call_later"
    Type "*tuple[Literal[10], Literal['player']]" is not assignable to type "*tuple[int, int, str]"
      "*tuple[Literal[10], Literal['player']]" is not assignable to "*tuple[int, int, str]"
        Tuple size mismatch; expected 3 but received 2 (reportArgumentType)
1 error, 0 warnings, 1 information

TypeVarTuple also describes tuple shapes, as with_index shows, and array shapes in numeric libraries. For decorators, ParamSpec is almost always the better choice, because it keeps keyword arguments, names and defaults, while *Ts only knows positional types.

The pre-3.12 spelling

On Python 3.10 and 3.11, declare the type variables at module level. The meaning is identical:

from collections.abc import Callable
from typing import Concatenate, ParamSpec, TypeVar
import functools
import sys

P = ParamSpec("P")
R = TypeVar("R")

def with_prefix(func: Callable[Concatenate[str, P], R]) -> Callable[P, R]:
    @functools.wraps(func)
    def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
        return func(">>", *args, **kwargs)
    return wrapper

@with_prefix
def show(prefix: str, msg: str) -> str:
    return f"{prefix} {msg}"

print(sys.version.split()[0], show("hi"))
3.10.11 >> hi

This was run with Python 3.10, and both checkers accept it with --python-version 3.10 / --pythonversion 3.10. For a TypeVarTuple before 3.11, use Ts = TypeVarTuple("Ts") from typing_extensions and write *args: Unpack[Ts] instead of *args: *Ts.

Related type hint topics: Typing Self, override and deprecated covers @override and @deprecated (which are decorators themselves), and TypedDict, Required, NotRequired and ReadOnly shows how to type **kwargs key by key with Unpack. Protocols, Literal and Final, and narrowing with TypeIs and TypeGuard, have their own articles in this chapter.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents