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

2 answers

  • answered 2021-01-11 05:18 U11-Forward

    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
    

  • answered 2021-01-11 05:23 Mark Tolonen

    Enums have built-in access by string and various ways of accessing the result. See the documentation for Enum for more details:

    from enum import Enum
    
    class Animal(Enum):
        Dog = 1
        Cat = 2
        Cow = 3 
    
    choice = input('Choose an animal: ')
    
    print(Animal[choice])
    print(repr(Animal[choice]))
    print(Animal[choice].value)
    
    Choose an animal: Cat
    Animal.Cat
    <Animal.Cat: 2>
    2