简体   繁体   English

如何使用 python 类型指定这种可变参数元组?

[英]How do I specify this kind of variable argument tuple with python typing?

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.目前没有一个注释可以表示固定长度元组与可变长度元组的添加。

here's some code I used to determine how mypy's inference would handle something like this:这是我用来确定 mypy 的推理如何处理这样的事情的一些代码:

from typing import Tuple

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

and output:和输出:

$ 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*]'

despite knowing that it's a variable-length int tuple it decays to object .尽管知道它是一个可变长度的int元组,但它会衰减为object

You may want to refactor your code to use Tuple[SignalNode, Tuple[Any, ...]] instead您可能希望重构代码以使用Tuple[SignalNode, Tuple[Any, ...]]代替

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM