6

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?

1
  • 3
    Why not name the fields as apple, cherry,.... with orderable values? The point of an enum is generally to have a comprehensive name but a practical value. You have an incomprehensive name for an impractical value. Oct 13, 2019 at 10:20

5 Answers 5

4

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
5
  • Is __eq__ needed for functools.total_ordering? Because Enum comes with an __eq__ that is much more efficient. Oct 14, 2019 at 18:17
  • Oh, I see, Enum uses default object.__eq__. So answering your question: yes, without reimplementing __eq__ my code will be more efficient. I implemented it because functools.total_ordering says it is needed: docs.python.org/3/library/… - "the class should supply an __eq__() method.". Maybe I just misunderstood this wording.
    – sanyassh
    Oct 14, 2019 at 18:33
  • Ah, I was mistaken -- Enum does not supply its own __eq__. Oct 14, 2019 at 20:08
  • @EthanFurman but accidentally default implementation of object.__eq__ works correctly for MyEnum. Try to remove __eq__ method from MyEnum - all comparisons will be correct.
    – sanyassh
    Oct 14, 2019 at 20:32
  • That's not an accident. ;-) I had just forgotten that I didn't need to implement __eq__ because object.__eq__ had the behavior we wanted. Oct 15, 2019 at 4:41
2

You can use IntEnums instead and use better names:

import enum

class Fruits(enum.IntEnum):
    Apple = 0
    Cherry = 1
    Banana = 2

print(Fruits.Apple < Fruits.Banana) 
print(Fruits.Banana >= Fruits.Cherry) 
print(Fruits.Cherry < Fruits.Apple)

Output:

True
True
False

IntEnums can be compared to each other and normal ints - so Fruits.Apple < 1000 is valid.

You can get the name or value from it like this:

>>> print(Fruits.Apple.name)
Apple

>>> print(Fruits.Apple.value)
0
4
  • my problem is that the values have to be something other than ints
    – retnikt
    Oct 13, 2019 at 19:27
  • 1
    IntEnum should only be used when compatibility with existing values is needed. Oct 13, 2019 at 19:50
  • @Ethan Why? Comparison especially mentions IntEnum as exception from the rule that Enums are not comparible. Your solution is neater then using IntEnum, but I was unable to find any "Don't do this" regarding using IntEnums if you want comparable Enums. Oct 14, 2019 at 5:17
  • Good point; down-vote removed. The "why" is that using IntEnum (or StrEnum, etc.) opens up the possibility of mistakenly comparing an enum against a different enum class or non-enum value -- in other words, you lose some type-safety. Oct 14, 2019 at 18:15
1

Using the OrderedEnum recipe as a start, it is easy to create your own ordered enum base class:

class OrderedEnum(Enum):

    def __init__(self, value, *args, **kwds):
        super().__init__(*args, **kwds)
        self.__order = len(self.__class__)

    def __ge__(self, other):
        if self.__class__ is other.__class__:
            return self.__order >= other.__order
        return NotImplemented

    def __gt__(self, other):
        if self.__class__ is other.__class__:
            return self.__order > other.__order
        return NotImplemented

    def __le__(self, other):
        if self.__class__ is other.__class__:
            return self.__order <= other.__order
        return NotImplemented

    def __lt__(self, other):
        if self.__class__ is other.__class__:
            return self.__order < other.__order
        return NotImplemented

And your example class becomes:

class MyEnum(OrderedEnum):
    A = "apple"
    C = "cherry"
    B = "banana"
4
  • using the incrementing len(self.__class__) is cool. super().__init__(*args, **kwds) should be super().__init__() Oct 14, 2019 at 5:10
  • @PatrickArtner: It's good practice to strip out the arguments needed for one's own class, and pass any others up the chain. If any were given to OrderedEnum, they should be passed up where they can either be used, or hit the end of the chain and raise an error. Oct 14, 2019 at 18:23
  • For me super().__init__(*args, **kwds) gives TypeError: object.__init__() takes no parameters in python 3.6 - so code does not work? Oct 14, 2019 at 20:29
  • @PatrickArtner: Ah, I was using aenum when I tested, and it isn't calling super(). I'll look into fixing that. Meanwhile, I adjusted the __init__ line to pull out value. Thanks for being persistent! Oct 15, 2019 at 4:52
0

you can override those operators in your enum class, it will be better for you to read about the data model here

if i would need to do it i would probably create a list of the elements ordered, and check it when calling does function, or change any element to be a tuple with index, and change the __get__ function

0

Assuming that your Enum class's __dict__ preserves Python 3.7's dictionary ordering semantics, you can get the order of the members like this:

>>> class E(enum.Enum):
...    A = 'apple'
...    C = 'cherry'
...    B = 'banana'
... 
>>> 
>>> members = [v for v in E.__dict__.values() if isinstance(v, E)]
>>> members
[<E.A: 'apple'>, <E.C: 'cherry'>, <E.B: 'banana'>]

The comparisons can then be made based on positions in the list.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.