Vijendran Selvarajah
Vijendran Selvarajah

Reputation: 1360

How to get the 'value' by dynamically passing the 'enum member name' in Python?

How to get the 'value' by dynamically passing the 'enum member name' in Python?

For an example consider the below enum

import enum 
class Animal(enum.Enum): 
    DOG = "This is Dog"
    CAT = "This is cat"
    LION = "This is Lion"

I want to write a common function something like below, and it has to return This is Dog.

def get_enum_value("DOG"):
    #
    # SOME CODE HERE TO GET THE VALUE FOR THE GIVEN (METHOD ARGUMENT) ENUM PROPERTY NAME 
    #

Upvotes: 5

Views: 4570

Answers (2)

Vijendran Selvarajah
Vijendran Selvarajah

Reputation: 1360

Simplified and full code :

## Enum definition
import enum 
class Animal(enum.Enum): 
    DOG = "This is Dog"
    CAT = "This is cat"
    LION = "This is Lion"


## method to return enum value when pass the enum member name
def get_enum_member_value(enum_member_name):
    enum_member_value = Animal[enum_member_name].value
    return enum_member_value


## execute the method and print the value     
print(get_enum_member_value("DOG"))

Upvotes: 5

Ethan Furman
Ethan Furman

Reputation: 69288

Answer based on question edit:

The functionality you're after is built in:

>>> Animal["DOG"].value
"This is Dog"

or

>>> member = "DOG"
>>> Animal[member].value
"This is Dog"

The only reason to make that a function would be for error handling -- for instance, if you want to gracefully handle a non-member name being passed in.


I see two possible questions (the names of your functions and usage of terminology are confusing):

  • How to get the .value property;
  • How to get the value of any property (the two built-in are value and name)

Actually, I know also see a third option:

  • How to get the value of property whose name is passed in (so get_enum_value is a method of Animal, not a separate function as your indentation would suggest)

Answering only the last question, the solution is something like:

import enum

class Animal(enum.Enum):
    #
    DOG = "This is Dog"
    CAT = "This is cat"
    LION = "This is Lion"
    #
    def get_enum_value(self, enum_property_name):
        return getattr(self, enum_property_name)

and in use:

>>> Animal.LION.get_enum_value('name')
'LION'

Upvotes: 2

Related Questions