mypy:如何将可变长度元组“转换”为固定长度元组?

时间:2019-02-26 09:39:26

标签: python mypy

Python代码:

t = (1,2,3)
t = tuple(x+1 for x in t)

mypy抱怨:

2: error: Incompatible types in assignment (expression has type "Tuple[int, ...]", variable has type "Tuple[int, int, int]")

该如何避免该错误?这没有帮助:

t = (1,2,3)
t = tuple(x+1 for x in t)[0:3]

此“有效”:

from typing import Tuple
t: Tuple[int, ...] = (1,2,3)
t = tuple(x+1 for x in t)

但是我实际上不希望t是一个可变长度的元组。

我当然可以告诉mypy忽略这一行:

t = (1,2,3)
t = tuple(x+1 for x in t) # type: ignore

或者重复我自己:

t = (1,2,3)
t = (t[0]+1, t[1]+1, t[2]+1)

或使用一个临时变量至少避免重复+1部分(在现实世界中这更复杂):

t = (1,2,3)
tmp = tuple(x+1 for x in t)
t = (tmp[0], tmp[1], tmp[2])

有更好的解决方案吗?

1 个答案:

答案 0 :(得分:1)

您可以使用cast来解决这个问题。

from typing import cast, Tuple

t = (1,2,3)

t = cast(Tuple[int, int, int], tuple(x+1 for x in t))