Python Glossary Русский

Python 3.11+typingterm

typing.TypeVarTuple

generics and parameters

A variadic type variable: it captures any number of types to type generics with a variable number of parameters (Python 3.11+).

Syntax

Ts = typing.TypeVarTuple('Ts')

A TypeVarTuple is almost never used alone — you unpack it with a star or via Unpack inside a Generic to capture a tail of arbitrarily many types (the canonical case is an array shape whose number of axes isn't known in advance). A plain TypeVar binds exactly one type, this one binds a whole sequence. Since Python 3.12 the same thing can be written with the built-in type-parameter syntax, without touching typing.

Examples

from typing import TypeVarTuple, Unpack
Ts = TypeVarTuple('Ts')
print(Ts.__name__)   # → Ts
# Python 3.12+
from typing import TypeVarTuple, Unpack, get_args
Ts = TypeVarTuple('Ts')
print(get_args(Unpack[Ts])[0] is Ts)  # → True
# Python 3.12+
def pack[*Us](*args: *Us) -> tuple[*Us]: return args
print(pack(1, 'a', True))   # → (1, 'a', True)
print(pack())   # → ()
print(pack.__type_params__[0].__name__)   # → Us

See also

Open in the full glossarydocs.python.orgReport an inaccuracy