[Python] Returning default members when Enum member does not exist

Discussão em 'Python' iniciado por Stack, Dezembro 17, 2024.

  1. Stack

    Stack Membro Participativo

    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?

    Continue reading...

Compartilhe esta Página