Sebastian
Sebastian

Reputation: 795

Python: How to get the name of an Enum?

A coworker who is on vacation has code that is similar to, for example:

from enum import Enum

class MyEnum(Enum):
    A = 1
    B = 2

def lookup(enum_type: Enum, value: str) -> Any:
    try:
        return enum_type[value]
    except ValueError:
        # PROBLEM IS HERE
        enum_name = ???
        raise ConfigurationError(enum_name, value)

Given an Enum like this, is there any way to retrieve its name? In this case, I would like to have enum_name = 'MyEnum'. We could do some parsing if necessary, but it would be very handy to just be able to get the name of the Enum.

In addition, PyCharm is giving me a warning on the lookup in:

return enum_type[value]

with suggestion:

Ignore an unresolved reference enum.Enum.__getitem__

Any help to clean this up would be appreciated. We are using Python 3.10. Any suggestions?

Upvotes: 2

Views: 1839

Answers (1)

Ethan Furman
Ethan Furman

Reputation: 69041

The name of the enum would be enum_type.__name__.

Be aware that the square bracket look-up (i.e. enum_type[value]) is actually looking up by member name, not member value. Member value would be enum_type(value).

Upvotes: 1

Related Questions