可变长度元组(可变元组)的类型提示?

问题描述 投票:0回答:3

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

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
确实适用于元组,我将它们用作可变长度的不可变列表。我在互联网上没有找到关于这个主题的任何共识,所以我想知道我应该如何注释这种输入。

python python-typing mypy
3个回答
273
投票

我们可以使用

...
文字(又名
Ellipsis
)来注释可变长度同质元组,如下所示:

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

Python3.9+

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

之后,错误就会消失。

来自文档

要指定同类类型的变长元组,请使用字面量 省略号,例如

Tuple[int, ...]
。普通的
Tuple
相当于
Tuple[Any, ...]
,然后依次为
tuple


14
投票

Python 3.9+

使用

tuple

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

自 Python 3.9 起,

typing.Tuple
已弃用。 typing.Tuple
文档
指出:

自 3.9 版本起已弃用builtins.tuple 现在支持

[]

Python 3.8 及更早版本

如果您使用的是 Python 3.8 或更早版本,您仍然应该使用

typing.Tuple
:

from typing import Tuple

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

8
投票

除了 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
© www.soinside.com 2019 - 2024. All rights reserved.