Search code examples
pythonclassenumsattributeerror

How can I access an enum member with an input in python


I am trying to access the value of the enum variables with an input.

Here is my code:

class Animals(Enum):
    Dog = 1
    Cat = 2
    Cow = 3 

Choose = input('Choose an animal')

print(Animals.Choose.value)

Which gives me an error perhaps because Animals does not contain Choose.

How can I distinguish between a member in the enum and my input variable?

So that if I input Dog it would give 1 (the value of the Dog variable)?


Solution

  • You can try using getattr:

    from enum import Enum
    class Animals(Enum):
        Dog = 1
        Cat = 2
        Cow = 3 
    
    
    Choose = input('Choose an animal')
    
    print(getattr(Animals, Choose).value)
    

    Output:

    1
    

    getattr stands for "get attribute", which means it gets the variable in the class which it's name is what the second argument is.

    Enums have already builtin __getitem__ methods, so you can directly index it with [] brackets, like this:

    print(Animals[Choose].value)
    

    Output:

    1