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.')
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.
Use the value attribute on each enum member to compare enums in Python, e.g. Sizes. LARGE. value > Sizes. MEDIUM.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With