mypy可以处理列表推导吗?

时间:2018-02-27 12:27:38

标签: python-3.x type-hinting mypy

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是否不处理此类列表推导或是否存在另一种定义类型的方法?

1 个答案:

答案 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)