pythonpython-typingmypy

Type hint for a tuple of variable length (variadic tuple)?


I have a function that takes a tuple of different lengths as an argument:

from typing import Tuple


def process_tuple(t: Tuple[str]):
    # Do nasty tuple stuff

process_tuple(("a",))
process_tuple(("a", "b"))
process_tuple(("a", "b", "c"))

When I annotate function like mentioned above, I get these error messages

fool.py:9: error: Argument 1 to "process_tuple" has incompatible type "Tuple[str, str]"; expected "Tuple[str]"
fool.py:10: error: Argument 1 to "process_tuple" has incompatible type "Tuple[str, str, str]"; expected "Tuple[str]"

process_tuple really works with tuples and I use them as immutable lists of variable length. I haven't found any consensus on this topic on the internet, so I wonder how should I annotate this kind of input.


Solution

  • We can annotate variable-length homogeneous tuples using the ... literal (aka Ellipsis) like this:

    def process_tuple(t: Tuple[str, ...]):
        ...
    

    or for Python3.9+

    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 literal ellipsis, e.g. Tuple[int, ...]. A plain Tuple is equivalent to Tuple[Any, ...], and in turn to tuple.

    More info about annotating tuples can be found at "Annotating tuples" section of the docs.