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 i
Solution 1:
Enum
was designed to not allow extending. Depending on your use-case, though, you have a couple options:
- build the enum dynamically from an external source (such as a json file). See When should I subclass EnumMeta instead of Enum? for the full details.
classCountry(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),
}
- use the
extend_enum
function theaenum
library:
extend_enum(ErrorCode, 'NEW_ERROR2', 'The new error 2')
Disclosure: I am the author of the Python stdlib Enum
, the enum34
backport, and the Advanced Enumeration (aenum
) library.
Post a Comment for "How To Extend The Python Class Attributes For Enum Derived Classes"