Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check ordering of items in a Python Enum?

Tags:

python

enums

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?

like image 881
retnikt Avatar asked Oct 13 '19 09:10

retnikt


1 Answers

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
like image 66
sanyassh Avatar answered Oct 23 '22 04:10

sanyassh