from typing import Tuple
def test_1(inp1: Tuple[int, int, int]) -> None:
pass
def test_2(inp2: Tuple[int, int, int]) -> None:
test_tuple = tuple(e for e in inp2)
reveal_type(test_tuple)
test_1(test_tuple)
在上面的代码上运行mypy
时,我得到:
error: Argument 1 to "test_1" has incompatible type "Tuple[int, ...]"; expected "Tuple[int, int, int]"
test_tuple
不能保证有3 int
个元素吗? mypy
是否不处理此类列表推导或是否存在另一种定义类型的方法?
答案 0 :(得分:0)
从版本0.600开始,mypy
在这种情况下不会推断类型。正如GitHub所建议的那样,很难实施。
相反,我们可以使用cast
(请参阅mypy docs):
from typing import cast, Tuple
def test_1(inp1: Tuple[int, int, int]) -> None:
pass
def test_2(inp2: Tuple[int, int, int]) -> None:
test_tuple = cast(Tuple[int, int, int], tuple(e for e in inp2))
reveal_type(test_tuple)
test_1(test_tuple)