如何将类型注释添加到可变长度元组?

How can I add type annotations to a variable length tuple?

我正在尝试(作为练习)键入 Curio 的源代码,但我在代码的生成部分中偶然发现了可变长度元组的问题。

Curio 的陷阱向内核生成一个已知长度的元组,但这些陷阱生成的元组长度彼此不同。

例如,curio.traps._read_wait(fileobj) 生成类型为 Tuple[int, int, int, str] 的 4 元组,而 curio.traps._spawn(coro) 生成类型为 Tuple[int, Coroutine].

的 2 元组

它们所有收益类型之间的相似之处在于,第一项始终是 int,但其余项的类型为 Any

在内核中,当它将协程运行到下一个屈服点时,它期望 int 作为第一项,然后是 Anys。我原以为 Tuple[int, Any, ...] 可能会起作用,但它给出了一个错误,指出 ... 是意外的。

from typing import Tuple, Any

# Test code
vltuple: Tuple[int, Any, ...] = (1, 2)
vltuple = (1, 2, 3)
vltuple = (1, 'a', 'b')
vltuple = (1, [], 4.5)

以下是确切的错误消息:

____.py:4: error: Unexpected '...'

____.py:4: error: Incompatible types in assignment (expression has type "Tuple[int]", variable has type "Tuple[int, Any, Any]")

正如我评论的那样:

According with , there can only be annotated Arbitrary-length homogeneous tuples as you see in PEP484 you cannot find any other reference to Arbitrary-length. It should be some hack but i recommend you to strip into 2 variables

解法:

key: int
args: list

key, *args = (1, 2)
key, *args = (1, 2, 3)
key, *args = (1, 'a', 'b')
key, *args = (1, [], 4.5)

通过使用扩展解包,您可以键入并分配固定数量的变量(在本例中,只有 key),额外的元素将放入另一个可以键入的变量中个别