mypy 可以处理列表推导式吗? [英] Can mypy handle list comprehensions?

查看:28
本文介绍了mypy 可以处理列表推导式吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 from 输入 import Tupledef test_1(inp1: Tuple[int, int, int]) ->没有任何:经过def test_2(inp2: Tuple[int, int, int]) ->没有任何:test_tuple = tuple(e for e inp2)揭示类型(测试元组)test_1(test_tuple)

在上面的代码上运行 mypy 时,我得到:

 错误:test_1"的参数 1 具有不兼容的类型Tuple[int, ...]";预期元组 [int,int,int]"

test_tuple 不能保证有 3 个 int 元素吗?mypy 不处理这样的列表推导式,还是有另一种定义类型的方法?

解决方案

从 0.600 版本开始,mypy 在这种情况下不会推断类型.正如 GitHub 所建议的那样,这将很难实施.>

相反,我们可以使用 cast(参见 mypy docs):

from 输入 import cast, Tupledef test_1(inp1: Tuple[int, int, int]) ->没有任何:经过def test_2(inp2: Tuple[int, int, int]) ->没有任何:test_tuple = cast(Tuple[int, int, int], tuple(e for e inp2))揭示类型(测试元组)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)

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?

解决方案

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)

这篇关于mypy 可以处理列表推导式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆