Validate against enumeration members in Python

In Python, I have an input (called input_var below) that I would like to check for an enumeration (called color below). Is the following approach recommended by Pythonic?

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.')
+4
source share
1 answer

Use the built-in function hasattr(). hasattr(object, name)returns Trueif it string nameis an attribute object, otherwise 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.')

Exit

Everything is fine and dandy.
+5
source

Source: https://habr.com/ru/post/1626521/


All Articles