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

2024-05-17 06:58:26 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

例如,curio.traps._read_wait(fileobj)生成Tuple[int, int, int, str]类型的4元组,而curio.traps._spawn(coro)生成{}类型的2元组。在

它们的所有收益类型之间的相似之处在于,第一项总是int,而其余的则是Any类型。在

在内核中,当它运行协程到下一个屈服点时,它期望一个int作为第一个项,然后是Any。我本来希望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]")


Tags: py类型curio错误anyerror内核int
1条回答
网友
1楼 · 发布于 2024-05-17 06:58:26

正如我所说:

According with this answer, 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)

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

相关问题 更多 >