8

I'm struggling with Python enums. I created an enum class containing various fields:

class Animal(Enum):
   DOG = "doggy"
   CAT = "cute cat"

I know that I can access this enum with value i.e. by passing Animal("doggy") I will have Animal.DOG. However I would like to achieve the same but the other way around, let's say I have "DOG" and I use it to find "doggy".

Example:

str_to_animal_enum("DOG") = Animal.DOG

I thought that I could rewrite init function of Enum class to check whether string name that we put as a parameter has representants in Enum names, if yes then we have a match.

Sth like this:

def __init__(cls, name):
   for enum in all_enums:
      if enum.name == name:
         return enum

But this solution looks very heavy in computation. Let's say that I have 100 names to find and for each name we have to make N iterations in the worst case scenario where N is number of enums in enum class.

I think there should be something better but I just don't know what. Do you have any ideas how it could be implemented? Thanks :)

JustPawel
  • 165
  • 1
  • 9
  • 2
    This isn't really how you are supposed to use enums, I would say. Enums are just constants that are more practically named; you appear to want to use them a bit like a (constant) dictionary, with a reverse look-up. – 9769953 Feb 18 '22 at 10:59
  • Yes you're completely right I didn't see that. Thank you for your help! – JustPawel Feb 18 '22 at 11:08

1 Answers1

14

As per the manual:

>>> Animal.DOG.value
'doggy'
>>> Animal.DOG.name
'DOG'
>>> # For more programmatic access, with just the enum member name as a string:
>>> Animal['DOG'].value
'doggy'
9769953
  • 10,344
  • 3
  • 26
  • 37