python - 为什么 mypy 在无法注释时提示列表理解?

标签 python mypy python-typing

当不可能使用 MyPy 注释这样的变量时,为什么 Mypy 提示它需要对列表理解变量进行类型注释?

具体来说,我该如何解决以下错误:

from enum import EnumMeta

def spam( y: EnumMeta ):
    return [[x.value] for x in y] 🠜 Mypy: Need type annotation for 'x' 

cast 不起作用 :
return [[cast(Enum, x).value] for x in y] 🠜 Mypy: Need type annotation for 'x'  

即使在这种情况下 Mypy 不支持注释( x:Enum ),我看到变量的 用法 可以使用 cast ( see this post )进行注释。然而,cast(Enum, x) 并没有阻止 Mypy 提示变量没有首先被注释。

#type: 不起作用 :
return [[x.value] for x in y] # type: Enum 🠜 Mypy: Misplaced type annotation

我还看到可以使用注释 for ( see this post ) 注释 # type: 循环变量。但是, # type: Enum 不适用于列表理解的 for

最佳答案

在列表推导式中,迭代器必须被强制转换而不是元素。

from typing import Iterable, cast
from enum import EnumMeta, Enum

def spam(y: EnumMeta):
    return [[x.value] for x in cast(Iterable[Enum], y)]

这也允许 mypy 推断 x 的类型。此外,在运行时它只执行 1 次强制转换而不是 n 次强制转换。

如果 spam 可以消化任何产生枚举的可迭代对象,则直接输入提示更容易。
from typing import Iterable
from enum import Enum

def spam(y: Iterable[Enum]):
    return [[x.value] for x in y]

关于python - 为什么 mypy 在无法注释时提示列表理解?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60669969/

相关文章:

c++ - 构建 jsoncpp (Linux) - 给我们凡人的指令?

python,从页面收集链接/脚本值

python - 无法加载 PROJ.4 库

python - Pandas 根据存在的列生成数据框

python - 如何在函数签名中引用 python 类属性的类型

python - 通过共享的任意类型耦合的抽象类的类型注释

python - 在单元测试中模拟对象时避免输入类型警告?

python - Mypy 不使用 Type[NamedTuple] 进行类型检查

python - 当类没有实现协议(protocol)时 mypy 不会提示

python - 如何在 Python 中创建用户定义类型断言?