Your solution will work in your specific Enum, but as I pointed in the comment: it will also change the behavior of all enums in the same application - including private enums used deep inside any library (and even enum's in the stdlib).
The "clean" way of doing this, following Object Oriented inheritance rules is to:
create a new metaclass, inheriting from the existing metaclass for Enum
, and update the __contains__
method in this class.
Then create a new Enum
base, using this new metaclass, but identical to Enum
in other respects (achieved by simply writing it with an empty body):
import enum
class CustomEnumMeta(enum.EnumMeta):
def __contains__(cls, element):
# Mocking "contains"
# It is usual to place "cls" instead of "self" in the metaclass
# as the received "instance" will be a class in itself.
return True
class CustomEnum(Enum, metaclass=CustomEnumMeta):
pass
class MyEnum(CustomEnum):
a = 1
b = 2
And in the interactive prompt:
In [10]: "x" in MyEnum
Out[10]: True
In [11]: MyEnum.a
Out[11]: <MyEnum.a: 1>
If you want to defer the to the normal containment rules after some custom logic, in the derived metaclass you can just call super().__contains__
after you are done with your personalized rules, like in:
...
def __contains__(cls, element):
if member in cls._member_map_:
return True
return super().__contains__(cls, element)
It is just a bit different from what you did, but it does not duplicate the logic of the original __contains__
in Enum in your custom method.