Sub topic 12
TypeVarTuple: variadic generics
This chapter assumes you know ordinary generic functions and classes (def f[T], class Box[T]) and can read tuple[int, str] annotations. You also need a static checker such as mypy or pyright, because the guarantees here come from the checker and not from the interpreter. The [*Ts] syntax needs Python 3.12. The *args: *Ts annotation form works from Python 3.11.
The problem: a variable number of types
A normal type variable stands for one type. That is not enough when the number of types can change from call to call. Consider a function that returns its positional arguments as a tuple:
def args_to_tuple_bad[T](*args: T) -> tuple[T, ...]:
return argsWith T, the checker unifies every argument into one type. Calling this with 1, "a", 2.5 gives tuple[int | str | float, ...]. The position-by-position information is lost: the checker no longer knows the first item is an int.
A TypeVarTuple solves this. It stands for a sequence of zero or more types, and the checker keeps each one separately.
Declaring and using *Ts
In the Python 3.12 syntax, you declare a TypeVarTuple by putting * before its name in the brackets. Wherever you use it, you unpack it again with *.
def args_to_tuple[*Ts](*args: *Ts) -> tuple[*Ts]:
return args
t = args_to_tuple(1, "a", 2.5) # checker infers tuple[int, str, float]
empty = args_to_tuple() # checker infers tuple[()]Read *args: *Ts as "the positional arguments have these types, in this order". Read tuple[*Ts] as "a tuple with exactly those types". The second call shows that zero types are allowed.
A bare Ts is an error in an annotation. It must always be unpacked, as *Ts, or as Unpack[Ts] in older code.
The legacy spelling
Before 3.12, you create the variable with TypeVarTuple("Ts"). Before 3.11, you also have to write Unpack[Ts] instead of *Ts inside annotations.
from typing import TypeVarTuple, Unpack
Ts = TypeVarTuple("Ts")
def args_to_tuple(*args: Unpack[Ts]) -> tuple[Unpack[Ts]]:
return argsThe two versions mean the same thing. Use the 3.12 form when your minimum Python version allows it.
Mixing fixed and variadic types
You can place ordinary types before or after *Ts. The checker matches the fixed ones first and gives whatever is left to *Ts.
def prepend[T, *Ts](item: T, rest: tuple[*Ts]) -> tuple[T, *Ts]:
return (item, *rest)
result = prepend(1, ("a", 2.5)) # T=int, Ts=(str, float)
# result: tuple[int, str, float]The diagram shows how the checker solves this call.
Variadic callables
A TypeVarTuple can describe the parameters of a callable. This is useful for helpers that forward arguments to another function and want the checker to verify them.
from collections.abc import Callable
def call_with[*Ts, R](func: Callable[[*Ts], R], *args: *Ts) -> R:
return func(*args)
def area(width: int, height: int) -> int:
return width * height
print(call_with(area, 3, 4)) # 12; checker infers int
# call_with(area, 3, "x") # a type checker reports an error hereThe checker reads Ts = (int, int) from area. It then requires the extra arguments to match (int, int).
Variadic classes
A class can take a TypeVarTuple too. Each type argument then occupies one position, and you subscript the class with any number of types.
class Row[*Ts]:
def __init__(self, *values: *Ts) -> None:
self.values: tuple[*Ts] = values
def as_tuple(self) -> tuple[*Ts]:
return self.values
r = Row(1, "a") # checker infers Row[int, str]
print(r.as_tuple()) # (1, 'a')A common real use is array shapes. Marker classes name the axes, and the type records which axes an array has and in what order.
class Height: ...
class Width: ...
class Channels: ...
class Array[*Shape]:
def __init__(self, *dims: int) -> None:
self.dims = dims
def resize(image: Array[Height, Width]) -> Array[Height, Width]:
return image
photo = Array[Height, Width, Channels](480, 640, 3)
flat = Array[Height, Width](480, 640)
resize(flat) # accepted
# resize(photo) # a type checker reports an error hereThe photo array carries one extra axis, so it does not match Array[Height, Width]. Numeric libraries use this idea to catch shape mistakes before the code runs.
Rules and limits
The rules are strict because the checker has to split a type list unambiguously.
- A type argument list or tuple can contain at most one unpacked
*Ts. A form liketuple[*Ts1, *Ts2]would have no unique solution, so it is rejected. - A
*argsparameter can be annotated with one*Ts, and**kwargscannot use it. - A
TypeVarTuplematches types by position. It does not capture names or keyword arguments. For whole signatures including keywords, useParamSpec. - Fixed types around
*Tsset a minimum length. Intuple[T, *Ts], an empty tuple is an error becauseTneeds one item. - A fixed-length tuple can match
*Tsexactly. A tuple liketuple[int, ...]matches as a single unpacked form,*tuple[int, ...], so the checker no longer knows the length. Most checkers handle that case, but results are looser.
Python 3.13 also lets a TypeVarTuple have a default, written as [*Ts = *tuple[int, str]]. It follows the same idea as the defaults in the earlier chapter on type parameter defaults.
Choosing the right tool
| Tool | Stands for | Typical use |
|---|---|---|
| `T` (TypeVar) | One type | Return the same type that came in |
| `**P` (ParamSpec) | A whole parameter list, including names and keywords | Decorators that keep a function's signature |
| `*Ts` (TypeVarTuple) | A sequence of types, by position | Tuples, `*args` forwarding, array shapes |
If you only forward a function's arguments untouched, ParamSpec is usually simpler. Use TypeVarTuple when the types themselves are the data, as in a tuple, a shape, or a row of values.
What exists at runtime
Like every generic feature in this tutorial, TypeVarTuple is for the checker. The interpreter keeps the objects, but it does not enforce them.
from typing import TypeVarTuple
class Row[*Ts]:
def __init__(self, *values: *Ts) -> None:
self.values = values
params = Row.__type_params__
print([p.__name__ for p in params]) # ['Ts']
print(isinstance(params[0], TypeVarTuple)) # True
r = Row[int, str](1, "a")
bad = Row[int, str]("x", 99, 3.0) # a type checker reports an error here
print(type(bad)) # <class '__main__.Row'>The class records its parameter in __type_params__, so tools can inspect it. Subscripting Row[int, str] works, but the call afterward performs no check. The wrong arguments in bad run without complaint, and the object's type is plain Row.
Common mistakes
- Writing
*args: Tsinstead of*args: *Ts. The bare variable is not valid in an annotation. - Using two unpacked variables in one tuple, such as
tuple[*A, *B]. - Expecting a runtime error from a mismatched
Row[int, str]call. - Using
TypeVarTuplewhereParamSpecfits better. Decorators that forward keyword arguments needParamSpec. - Using the 3.12
[*Ts]syntax in a project that still supports Python 3.11 or earlier.
Exercise
Write a generic function swap_ends that is supposed to move the first item of a tuple to the end, and say what type the checker would infer for swap_ends((1, "a", 2.5)). Write the signature using the Python 3.12 syntax, and give a body that runs correctly.
Show answer
def swapends[T, Ts](values: tuple[T, Ts]) -> tuple[Ts, T]:
first, rest = values
return (*rest, first)
The checker infers tuple[str, float, int] for swapends((1, "a", 2.5)). T binds to int and Ts binds to (str, float). The result at runtime is ('a', 2.5, 1). The signature is correct, but some checkers cannot prove the body matches it. If yours reports an error on the return line, add a # type: ignore comment there, since the signature is what callers rely on.
Exercise
Why does Row[int, str]("x", 99, 3.0) run without an error, and what would catch the mistake?
Show answer
Type arguments are erased from checking at runtime. The class object accepts the subscript and the call, and nothing compares the values to int and str. A static type checker such as mypy or pyright would report the mismatch before the program runs. To catch it while the program runs, you would have to write an explicit check in the code.