Sub topic 12
TypeVarTuple: variadic generics
This chapter assumes you can write generic functions and classes with the Python 3.12 [T] syntax and that you know what a type checker such as mypy or pyright does. A TypeVar stands for one type. A TypeVarTuple stands for any number of types, including zero.
The problem it solves
Suppose a function takes any number of positional arguments and returns them as a tuple. With a plain TypeVar, every argument would need the same type. With tuple[object, ...], the checker forgets which type sits at which position.
A TypeVarTuple keeps the whole sequence of types. You declare it with a leading * in the type parameter list.
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[()]Here *Ts is the type parameter. In *args: *Ts, the second star unpacks the types, so each argument gets its own type. In tuple[*Ts], the star expands those types into the tuple's element types.
Mixing fixed and variadic parts
You can put ordinary type parameters next to a TypeVarTuple. The checker matches the fixed positions first, and Ts takes whatever remains.
def head[T, *Ts](values: tuple[T, *Ts]) -> T:
return values[0]
def tail[T, *Ts](values: tuple[T, *Ts]) -> tuple[*Ts]:
_, *rest = values
return tuple(rest)
h = head((1, "a", 2.5)) # int
r = tail((1, "a", 2.5)) # tuple[str, float]tail shows the main benefit. The result type is computed from the input type, so the checker knows r holds a str and then a float.
Variadic classes
A class can take a TypeVarTuple too. A common use is a typed row container, where each row has the same column types.
class Table[*Ts]:
def __init__(self) -> None:
self.rows: list[tuple[*Ts]] = []
def add(self, *row: *Ts) -> None:
self.rows.append(row)
people = Table[str, int]()
people.add("Ada", 36)
people.add("Alan", 41)
# people.add("Grace") # a checker reports a missing intForwarding arguments to a callable
TypeVarTuple also fits inside Callable. This lets a helper accept a function and exactly the arguments that function needs.
from collections.abc import Callable
def call_with[*Ts, R](func: Callable[[*Ts], R], *args: *Ts) -> R:
return func(*args)
def join(sep: str, count: int) -> str:
return sep * count
result = call_with(join, "-", 3) # str
# call_with(join, "-", "3") # a checker reports the wrong typeFor forwarding keyword arguments and defaults, use ParamSpec instead. TypeVarTuple only covers positional types.
Rules and common errors
| Mistake | What happens |
|---|---|
| Writing `tuple[Ts]` without a star | The checker reports that `Ts` must be unpacked. |
| Annotating `*args: Ts` without a star | Same error. Use `*args: *Ts`. |
| Declaring two `TypeVarTuple`s in one tuple or signature | Ambiguous, so checkers reject it. The checker cannot tell where one ends and the next begins. |
| Expecting a runtime check | None happens. See the callout below. |
When to use it
Reach for TypeVarTuple when the number of types is unknown and their order matters: array shapes, typed rows, and wrappers that forward positional arguments. If every element has the same type, use Sequence[T]. If the length is fixed and small, use ordinary type parameters.
Exercise
Write a generic function last that takes a tuple with at least one element and returns its final element. Use a TypeVarTuple so that last((1, "a", 2.5)) is inferred as float.
Show answer
def last[Ts, T](values: tuple[Ts, T]) -> T: return values[-1] The fixed parameter T goes after the unpacked *Ts in the tuple, so the checker assigns the last position to T and everything before it to Ts. Passing (1, "a", 2.5) gives Ts = (int, str) and T = float.