mypy:如何将 "convert" 可变长度元组变回固定长度元组?
mypy: How to "convert" variable length tuple back to fixed length tuple?
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]
这个"works":
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])
有没有更好的解决方案?
您可以使用 cast 来解决这个问题。
from typing import cast, Tuple
t = (1,2,3)
t = cast(Tuple[int, int, int], tuple(x+1 for x in t))
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]
这个"works":
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])
有没有更好的解决方案?
您可以使用 cast 来解决这个问题。
from typing import cast, Tuple
t = (1,2,3)
t = cast(Tuple[int, int, int], tuple(x+1 for x in t))