In this lesson, you will learn how to use TypeVarTuple to maintain strict type safety when creating functions that accept an arbitrary number of arguments of different, specific types.
The Problem with *args
When you define a function that takes *args: Any, you lose all information about what those arguments actually are. If you want to return a tuple containing exactly the items passed in, a standard TypeVar isn't enough because it can only represent one single type.
Enter TypeVarTuple
Introduced in PEP 646, TypeVarTuple allows you to define a "variadic" type variable—essentially a placeholder for a variable-length sequence of types. This allows the static type checker (like Mypy) to "track" each individual type within the tuple.
Consider a simple function that prepends a string to a sequence of various types:
from typing import TypeVarTuple, Unpack
Ts = TypeVarTuple("Ts")
def prepend_header(header: str, *args: Unpack[Ts]) -> tuple[str, Unpack[Ts]]:
return (header, *args)
# The type checker knows this result is (str, int, float)
result = prepend_header("Data", 1, 2.5)
Breaking it Down
TypeVarTuple("Ts"): This declaresTsas a collection of types, rather than a single type.Unpack[Ts]: Think of this as the type-hinting equivalent of the*operator. It tells the type checker to "unpack" the individual types stored in theTsvariadic variable.- Preservation: Because we used
Unpack[Ts]in both the arguments and the return type, Python keeps the mapping intact. If you pass anintas the first argument, the type checker knows the corresponding element in the return tuple is anint.
This is significantly more powerful than using *args: Any because it prevents type errors that would otherwise be invisible until runtime. It is the gold standard for creating decorators, factory functions, or data pipelines that need to be both flexible and strictly typed.
Key Takeaway: Use TypeVarTuple combined with Unpack to allow your functions to accept a variable number of arguments while preserving the specific type of each individual input.