6
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处理这样的列表推导,还是有另一种在这里定义类型的方法?

4

1 回答 1

6

从 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)
于 2018-05-17T14:57:52.540 回答