如何注释采用可变长度元组的函数?(可变元组类型注释) [英] How to annotate function that takes a tuple of variable length? (variadic tuple type annotation)

查看:34
本文介绍了如何注释采用可变长度元组的函数?(可变元组类型注释)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个将不同长度的元组作为参数的函数:

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

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.

推荐答案

Variable length homogeneous tuple we can annotate using ...literal (aka Ellipsis) like

Variable length homogeneous tuple we can annotate using ... literal (aka Ellipsis) like

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

在那之后错误应该会消失.

after that errors should go away.

来自文档

要指定同构类型的可变长度元组,请使用字面量省略号,例如元组[int, ...].一个普通的 Tuple 等价于Tuple[Any, ...],依次为tuple.

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.

这篇关于如何注释采用可变长度元组的函数?(可变元组类型注释)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆