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 :)