mypy 可以处理列表推导式吗?

alk*_*mid 5 python type-hinting python-3.x 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)
Run Code Online (Sandbox Code Playgroud)

mypy上面的代码上运行时,我得到:

error: Argument 1 to "test_1" has incompatible type "Tuple[int, ...]"; expected "Tuple[int, int, int]"
Run Code Online (Sandbox Code Playgroud)

test_tuple不能保证有3个int要素是什么?难道mypy没有处理此类列表理解或有此定义类型的另一种方式?

alk*_*mid 7

从版本 0.600 开始,mypy在这种情况下不会推断类型。正如GitHub上的建议,这很难实现。

相反,我们可以使用cast(参见mypy 文档):

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)
Run Code Online (Sandbox Code Playgroud)