pythonenums

Returning default members when Enum member does not exist


I have an Enum where I would like a default member to be returned when a member does not exist inside of it. For example:

class MyEnum(enum.Enum):
    A = 12
    B = 24
    CUSTOM = 1


print(MyEnum.UNKNOWN) # Should print MyEnum.CUSTOM

I know I can use a metaclass like so:

class MyMeta(enum.EnumMeta):
    def __getitem__(cls, name):
        try:
            return super().__getitem__(name)
        except KeyError as error:
            return cls.CUSTOM

class MyEnum(enum.Enum,metaclass=MyMeta):
    ...

But that appears to only work if I access the Enum using MyEnum['UNKNOWN']. Is there a way that covers both methods of accessing members of an enum when the member doesn't exist?


Solution

  • Add a definition for __getattr__ to the metaclass:

    class MyMeta(enum.EnumMeta):
        def __getitem__(cls, name):
            try:
                return super().__getitem__(name)
            except KeyError as error:
                return cls.CUSTOM
        
        def __getattr__(cls, name):
            try:
                return super().__getattr__(name)
            except AttributeError as error:
                return cls.CUSTOM
    

    Then, your code will output:

    MyEnum.CUSTOM