I have an enum.Enum
subclass:
class MyEnum(Enum):
A = "apple"
C = "cherry"
B = "banana"
and I want to be able to use <
and >
to see if a given member comes before or after another one in the definition order, so I could do something like this:
>>> MyEnum.A < MyEnum.B
True
>>> MyEnum.B >= MyEnum.C
True
>>> MyEnum.C < MyEnum.A
False
based on where the values appear in the definitions of the enum, not the enum values themselves. I know that Enums preserve order, but there is no way of finding which came first. How can I accomplish this in Python 3.7?
You need to override comparison operators and somehow check the order of names of compared enum members. I found that _member_names_
preserve the order of defined members:
from enum import Enum
import functools
@functools.total_ordering
class MyEnum(Enum):
A = "apple"
C = "cherry"
B = "banana"
def __eq__(self, other):
if isinstance(other, MyEnum):
return (
self._member_names_.index(self.name) ==
self._member_names_.index(other.name)
)
return NotImplemented
def __gt__(self, other):
if isinstance(other, MyEnum):
return (
self._member_names_.index(self.name) >
self._member_names_.index(other.name)
)
return NotImplemented
print(MyEnum.A < MyEnum.B) # True
print(MyEnum.B >= MyEnum.C) # True
print(MyEnum.C < MyEnum.A) # False
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