5

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 # 
2
  • What do you mean by enum property? DOG is an enum member, while name is an enum property, as is value Commented Dec 12, 2019 at 16:50
  • Sorry for the for the confusion. I have edited the question. Hope it make sense now. Commented Dec 13, 2019 at 3:37

2 Answers 2

5

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")) 
Sign up to request clarification or add additional context in comments.

Comments

2

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' 

3 Comments

Sorry for the confusion. I have edited the question and hope make sense now. I'm looking for a function which I has to return "This is Dog" when I pass "Dog" in the parameter.
@VijendranSelvarajah: No problem; I added more content to the top of my answer.
The third option should not be used as you can pass arbitrary method and attribute names, e.g. "init"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.