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

问题描述 投票:0回答:1
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
是否不处理此类列表推导式,或者是否有另一种方法在这里定义类型?

python python-typing mypy
1个回答
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)
© www.soinside.com 2019 - 2024. All rights reserved.