问题
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