为什么Mypy在无法注释列表时抱怨列表理解?

问题描述 投票:0回答:1

为什么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),在这种情况下,我也可以使用castsee 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

python mypy python-typing
1个回答
0
投票

在列表理解中,必须强制转换迭代器而不是元素。

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]
© www.soinside.com 2019 - 2024. All rights reserved.