mypy 可以处理列表理解吗?
Can mypy handle list comprehensions?
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
是否不处理此类列表理解,或者是否有另一种定义类型的方法?
从 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)
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
是否不处理此类列表理解,或者是否有另一种定义类型的方法?
从 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)