如何使用python类型指定这种可变参数元组? [英] How do I specify this kind of variable argument tuple with python typing?

查看:191
本文介绍了如何使用python类型指定这种可变参数元组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试这样做,但是我不确定如何指定类型签名:

I'm trying to do this, but I'm not sure how to specify the type signature:

def initialize_signals(
        self,
        command: InitializeCommand,
        initializers: Iterable[Union[
            Tuple[SignalNode],
            Tuple[SignalNode, Any, ...]
                  ]]):
    for x, *args in initializers:
        potential_update = command.create_potential_update(x, *args)

推荐答案

当前没有注释可以表示添加了固定长度元组和可变长度元组.

there currently isn't an annotation which can represent the addition of a fixed-length tuple with a variable length tuple.

下面是一些我用来确定mypy的推理如何处理此类代码的代码:

here's some code I used to determine how mypy's inference would handle something like this:

from typing import Tuple

x: Tuple[int, ...]
y = ('hi', *x)
z = (*x,)
reveal_type(y)
reveal_type(z)

并输出:

$ mypy t.py
t.py:6: error: Revealed type is 'builtins.tuple[builtins.object*]'
t.py:7: error: Revealed type is 'builtins.tuple[builtins.int*]'

尽管知道这是一个可变长度的int元组,但它会衰减为object.

despite knowing that it's a variable-length int tuple it decays to object.

您可能希望重构代码以改为使用Tuple[SignalNode, Tuple[Any, ...]]

You may want to refactor your code to use Tuple[SignalNode, Tuple[Any, ...]] instead

这篇关于如何使用python类型指定这种可变参数元组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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