2
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.

Joelster
  • 339
  • 3
  • 15
  • Probably, you just shouldn't use an enum, especially if you are just going to inherit from string, which sort of defeats the entire point. In any case, this isn't working because all the enum magic happens with metaclass machinery that works with the class as it is being instantiated. Note, your class, `ErrorCode`, does in fact have that attribute. – juanpa.arrivillaga Jul 26 '21 at 04:50
  • 1
    Why are you using `Enum('NEW_ERROR2', 'The new error 2')`?? That creates (perhaps confusingly) an entirely new enum *class* – juanpa.arrivillaga Jul 26 '21 at 04:51
  • @juanpa.arrivillaga: For new enums, inheriting from `str` is probably not necessary; but if replacing existing string constants then it's entirely appropriate. – Ethan Furman Jul 26 '21 at 17:30

1 Answers1

4

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.

Ethan Furman
  • 63,992
  • 20
  • 159
  • 237
  • Thanks @Ethan Furman had a look and that does look useful in certain use cases. Given the above feedback and some further time to think about the issue at hand, I think I'm going to move away from Enums for now and try some other structures. – Joelster Jul 26 '21 at 19:37