为什么Mypy无法使用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
(# type:
)注释see this post循环变量。但是,# 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
可以消化生成枚举的any可迭代对象,则直接键入提示将更容易。
from typing import Iterable
from enum import Enum
def spam(y: Iterable[Enum]):
return [[x.value] for x in y]