Can mypy handle list comprehensions?

穿精又带淫゛_ 提交于 2020-02-03 16:18:33

问题


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)

While running mypy on the above code, I get:

error: Argument 1 to "test_1" has incompatible type "Tuple[int, ...]"; expected "Tuple[int, int, int]"

Is test_tuple not guaranteed to have 3 int elements? Does mypy not handle such list comprehensions or is there another way of defining the type here?


回答1:


As of version 0.600, mypy does not infer types in such cases. It would be hard to implement, as suggested on GitHub.

Instead, we can use cast (see 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)


来源:https://stackoverflow.com/questions/49008718/can-mypy-handle-list-comprehensions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!