11

In Python, I have an input (called input_var below) that I would like to validate against a enum (called Color below). Is the following way the recommended Pythonic approach?

from enum import Enum
class Color(Enum):
    red = 1
    blue = 2
input_var = 'red'
if input_var in Color.__members__:
    print('Everything is fine and dandy.')

1 Answer 1

13

Use the built-in hasattr() function. hasattr(object, name) returns True if the string name is an attribute of object, else it returns False.

Demo

from enum import Enum

class Color(Enum):
    red = 1
    blue = 2

input_var = 'red'

if hasattr(Color, input_var):
    print('Everything is fine and dandy.')

Output

Everything is fine and dandy.
Sign up to request clarification or add additional context in comments.

1 Comment

This will return true for hasattr(Color, 'mro'). You may want if hasattr(Color, input_var) and input_var != 'mro'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.