如何为 Enum derived classes 扩展 Python class 属性

How to extend the Python class attributes for Enum derived classes

from enum import Enum

class ErrorCode(str, Enum):
    GENERAL_ERROR = 'A general error has occurred.'
    INVALID_RECIPIENT_EMAIL_ADDRESS = 'The recipient email address provided is not a valid email address.'

    @classmethod
    def addErrorsAsAttrib(cls, err_code, err_description):
        setattr(cls, err_code, err_description)

extended_error_codes = ErrorCode.addErrorsAsAttrib('NEW_ERROR2', Enum('NEW_ERROR2', 'The new error 2'))

print(ErrorCode.__members__.keys())

# OUTPUT:
# dict_keys(['GENERAL_ERROR', 'INVALID_RECIPIENT_EMAIL_ADDRESS'])

我正在尝试找到一种方法将新错误代码动态添加到我的错误代码 class(一个枚举派生的 class),但无法确定执行此操作的正确方法。根据代码示例 - 我尝试了 setattr() 但这没有按预期执行。任何帮助将不胜感激。

Enum 被设计为不允许扩展。不过,根据您的用例,您有几个选择:

  • 从外部源(例如 json 文件)动态构建枚举。有关完整详细信息,请参阅
    class Country(JSONEnum):
        _init_ = 'abbr code country_name'  # remove if not using aenum
        _file = 'some_file.json'
        _name = 'alpha-2'
        _value = {
                1: ('alpha-2', None),
                2: ('country-code', lambda c: int(c)),
                3: ('name', None),
                }
    extend_enum(ErrorCode, 'NEW_ERROR2', 'The new error 2')

1 披露:我是 Python stdlib Enum, the enum34 backport, and the Advanced Enumeration (aenum) 库的作者。