【问题标题】:Why is mypy complaining about list comprehension when it can't be annotated?当无法注释时,为什么 mypy 会抱怨列表理解?
【发布时间】: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


    【解决方案1】:

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

    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 可以消化任何产生枚举的迭代,直接输入hint this 会更容易。

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

    【讨论】:

      【解决方案2】:

      MisterMyagi 的answer 是针对这种特定情况的最佳解决方案。然而,值得注意的是,也可以在定义变量之前声明变量的类型。下面还有passes MyPy

      from enum import Enum
      
      def spam(y: type[Enum]):
          x: Enum
          return [[x.value] for x in y]
      

      【讨论】:

        猜你喜欢
        • 2023-02-10
        • 2019-07-22
        • 1970-01-01
        • 2022-01-10
        • 2021-09-29
        • 2023-04-02
        • 2021-02-25
        • 1970-01-01
        相关资源
        最近更新 更多