How to annotate function that takes a tuple of variable length? (variadic tuple type annotation)
We can annotate variable-length homogeneous tuples using the ...
literal (aka Ellipsis
) like this:
def process_tuple(t: Tuple[str, ...]): ...
After that, the errors should go away.
From the docs:
To specify a variable-length tuple of homogeneous type, use literalellipsis, e.g.
Tuple[int, ...]
. A plainTuple
is equivalent toTuple[Any, ...]
, and in turn totuple
.
In addition to the Ellipsis answer as posted by Azat you could make it more explicit by using @typing.overload
or typing.Union
from typing import Tuple@overloaddef process_tuple(t: Tuple[str]): # Do nasty tuple stuff@overloaddef process_tuple(t: Tuple[str, str]): ...
Or with the Union:
from typing import Tuple, Uniondef process_tuple(t: Union[Tuple[str], Tuple[str, str], Tuple[str, str, str]]): # Do nasty tuple stuff