Contain check in Enum values

Viewed 52

How can contain check against Enum values can be made?

class MyEnum(Enum):
    foo = 'FOO'
    bar = 'BAR'

I have already tried:

'zzz' in  class.__members__.values()

Could you point me the way?

2 Answers

You can get the set of all values of the Enum and check using in membership operation

enum_values = {e.value for e in MyEnum}
print('FOO' in enum_values)
print('zzz' in enum_values)

The output will be

True
False

You can list and check the values like this:

def checkIfValueContainsInEnum(value):
    enumValues = [item.value for item in MyEnum]  # [4, 5, 6]
    if value in enumValues:
        return True
    else:
        return False
Related