如何注释一个可变长度的元组的函数? (可变元组类型注释)

我有一个函数,它使用不同长度的元组作为参数:

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"))


当我像上面提到的那样对函数进行注释时,我会得到这些错误消息

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确实与元组一起工作,我使用它们作为可变长度的不可变列表。我还没有在网上找到任何关于这个话题的共识,所以我想知道我应该如何注释这种投入。

36393 次浏览

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.

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




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


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

Or with the Union:

from typing import Tuple, Union




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

Python 3.9+

Use tuple:

def process_tuple(t: tuple[str, ...]):
pass

Since Python 3.9, typing.Tuple is deprecated. The documentation for typing.Tuple states:

Deprecated since version 3.9: builtins.tuple now supports [].

Python 3.8 and earlier

If you are on Python 3.8 or earlier, you should still use typing.Tuple:

from typing import Tuple


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