Preserve Tuple Shapes with TypeVarTuple
Core idea
TypeVarTuple represents a variable-length sequence of types, unlike a single TypeVar. Unpack expands that sequence into tuple positions, so a function can add an item while retaining the other positions. Both are available from Python 3.11.
from typing import TypeVarTuple,UnpackTs=TypeVarTuple('Ts')def label(row:tuple[Unpack[Ts]])->tuple[str,Unpack[Ts]]: return ('item',*row)print(label((3,True)))The checker can retain int and bool as separate positions; unpacking constructs the tuple.
Capture a variadic argument sequence
from typing import TypeVarTuple,UnpackTs=TypeVarTuple('Ts')def pack(*args:Unpack[Ts])->tuple[Unpack[Ts]]: return argsprint(pack(5,'ok'), pack())The shape may contain any number of positions, including zero.
Common mistake
TypeVarTuple is not ParamSpec: it models positional type sequences, not named callable parameters. It must be unpacked in a type expression.
Practice
Write a function adding an integer at the end of a heterogeneous tuple, then inspect the inferred result in a checker.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
TypeVarTuple and Unpack
Check your understanding of typevartuple and unpack.
What is printed?
from typing import TypeVarTupleTs=TypeVarTuple('Ts')print(Ts.__name__)What is printed?
def f(*args): return ('x',*args)print(f(2,False))Which tool represents several positional types?
Can the captured type sequence be empty?