Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate against enum members in Python

Tags:

python

enums

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.')
like image 243
Richard Foo Avatar asked Jan 29 '16 12:01

Richard Foo


People also ask

How do you validate enum values in Python?

To check if a value exists in an enum in Python:Use a list comprehension to get a list of all of the enum's values. Use the in operator to check if the value is present in the list. The in operator will return True if the value is in the list.

How do I compare two enums in Python?

Use the value attribute on each enum member to compare enums in Python, e.g. Sizes. LARGE. value > Sizes. MEDIUM.


1 Answers

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.
like image 84
gtlambert Avatar answered Oct 04 '22 03:10

gtlambert