Tuple types
The type Tuple[T1, …, Tn]
represents a tuple with the item types T1
, …, Tn
:
- def f(t: Tuple[int, str]) -> None:
- t = 1, 'foo' # OK
- t = 'foo', 1 # Type check error
A tuple type of this kind has exactly a specific number of items (2 inthe above example). Tuples can also be used as immutable,varying-length sequences. You can use the type Tuple[T, …]
(witha literal …
– it’s part of the syntax) for thispurpose. Example:
- def print_squared(t: Tuple[int, ...]) -> None:
- for n in t:
- print(n, n ** 2)
- print_squared(()) # OK
- print_squared((1, 3, 5)) # OK
- print_squared([1, 2]) # Error: only a tuple is valid
Note
Usually it’s a better idea to use Sequence[T]
instead of Tuple[T, …]
, asSequence
is also compatible with lists and other non-tuple sequences.
Note
Tuple[…]
is valid as a base class in Python 3.6 and later, andalways in stub files. In earlier Python versions you can sometimes work around thislimitation by using a named tuple as a base class (see section Named tuples).