Python Enum class membership
Enum does have a __contains__
method, but it checks for member names rather than member values:
def __contains__(cls, member):
return isinstance(member, cls) and member._name_ in cls._member_map_
Internally(in CPython) they do have a private attribute that maps values to names(will only work for hashable values though):
>>> 2 in TestEnum._value2member_map_
True
>>> 3 in TestEnum._value2member_map_
False
But it's not a good idea to rely on private attributes as they can be changed anytime, hence you can add your own method that loops over __members__.values()
:
>>> class TestEnum(Enum):
... a = 0
... b = 1
... c = 2
...
... @classmethod
... def check_value_exists(cls, value):
... return value in (val.value for val in cls.__members__.values())
...
>>>
>>> TestEnum.check_value_exists(2)
True
>>> TestEnum.check_value_exists(3)
False