Joelster
Joelster

Reputation: 349

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'])

I am trying to find a way to dynamically add new Error Codes to my ErrorCode class (an Enum derived class) but just cannot determine the correct way to do this. As per the code sample - I tried setattr() but this does not perform as expected. Any help would be appreciated.

Upvotes: 2

Views: 2982

Answers (1)

Ethan Furman
Ethan Furman

Reputation: 69120

Enum was designed to not allow extending. Depending on your use-case, though, you have a couple options:

    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 Disclosure: I am the author of the Python stdlib Enum, the enum34 backport, and the Advanced Enumeration (aenum) library.

Upvotes: 5

Related Questions