我有一个函数,将不同长度的元组作为参数:
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
确实适用于元组,我将它们用作可变长度的不可变列表。我尚未在互联网上找到关于此主题的任何共识,因此我想知道该如何注释这种输入。
答案 0 :(得分:6)
我们可以使用...
文字(也称为Ellipsis
)来注释可变长度的均等元组
def process_tuple(t: Tuple[str, ...]):
...
此后错误应该消失。
来自docs
要指定同构类型的变长元组,请使用文字 省略号,例如
Tuple[int, ...]
。普通的Tuple
等效于Tuple[Any, ...]
,然后依次转到tuple
。
答案 1 :(得分:1)
除了Azat发布的省略号答案之外,您还可以使用@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