我有一个函数,它接受不同长度的元组作为参数:
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
确实适用于元组,我将它们用作可变长度的不可变列表。我在互联网上没有找到关于这个主题的任何共识,所以我想知道我应该如何注释这种输入。
我们可以使用
...
文字(又名 Ellipsis
)来注释可变长度同质元组,如下所示:
def process_tuple(t: Tuple[str, ...]):
...
或Python3.9+
def process_tuple(t: tuple[str, ...]):
...
之后,错误就会消失。
来自文档:
要指定同类类型的变长元组,请使用字面量 省略号,例如
。普通的Tuple[int, ...]
相当于Tuple
,然后依次为Tuple[Any, ...]
。tuple
使用
tuple
:
def process_tuple(t: tuple[str, ...]):
pass
自 Python 3.9 起,
typing.Tuple
已弃用。 typing.Tuple
的 文档指出:
自 3.9 版本起已弃用:builtins.tuple 现在支持
。[]
如果您使用的是 Python 3.8 或更早版本,您仍然应该使用
typing.Tuple
:
from typing import Tuple
def process_tuple(t: Tuple[str, ...]):
pass
@typing.overload
或 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]):
...
或与工会:
from typing import Tuple, Union
def process_tuple(t: Union[Tuple[str], Tuple[str, str], Tuple[str, str, str]]):
# Do nasty tuple stuff