You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何不使用type: ignore解决继承str的Enum用auto()时MyPy报错问题

解决方法

方案1:Python 3.11+ 直接使用标准库内置StrEnum

Python 3.11版本开始,标准库enum模块已经原生提供了StrEnum类,默认auto()就会返回枚举名称的字符串值,MyPy对其有原生类型支持,无需自定义基类,直接使用即可无报错:

from enum import StrEnum, auto

class Foo(StrEnum):
    bar = auto()
    baz = auto()

def takes_a_string(s: str):
   pass

takes_a_string(s=Foo.bar)

方案2:Python 3.10及以下版本,修正自定义StrEnum的实现

原有代码的报错来自两处问题:

  • _generate_next_value_是Enum类约定的静态方法,不加@staticmethod装饰器会被MyPy识别为实例方法,触发签名不兼容、缺失self参数的报错
  • 没有给方法加明确的返回值类型注解,MyPy无法推断auto()生成的枚举值为str类型,会误判为auto类型
    修正后的完整代码如下:
from enum import Enum, auto
from typing import Any, List

class StrEnum(str, Enum):
    @staticmethod
    def _generate_next_value_(name: str, start: int, count: int, last_values: List[Any]) -> str:
        return name

class Foo(StrEnum):
    bar = auto()
    baz = auto()

def takes_a_string(s: str):
   pass

takes_a_string(s=Foo.bar)

修正后MyPy不会触发任何类型错误,也不需要加# type: ignore标记。

内容的提问来源于stack exchange,提问作者sid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 23:54:04