【发布时间】:2020-06-25 10:34:10
【问题描述】:
当无法使用 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。
【问题讨论】:
标签: python type-hinting mypy python-typing