当不可能使用 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/