How to compare Enums in Python

avatar

Borislav Hadzhiev

Last updated: Jun 17, 2022

banner

Photo from Unsplash

Comparing Enums in Python #

Use the value attribute on each enum member to compare enums in Python, e.g. Sizes.LARGE.value > Sizes.MEDIUM.value. The value attribute on the enum member returns the literal that can be used to safely compare enum values.

main.py
class Sizes(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 # 👇️ True print(Sizes.LARGE.value > Sizes.MEDIUM.value) # 👇️ True print(Sizes.MEDIUM.value < Sizes.LARGE.value) # 👇️ False print(Sizes.SMALL.value == Sizes.LARGE.value)

We used the value attribute on members of the enum to get integer values that we can safely compare.

main.py
class Sizes(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 print(Sizes.SMALL.value) # 👉️ 1 print(Sizes.MEDIUM.value) # 👉️ 2 print(Sizes.LARGE.value) # 👉️ 3

You can also use square brackets to access the enum member if you don't know its name ahead of time.

main.py
class Sizes(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 name_1 = 'LARGE' name_2 = 'SMALL' # 👇️ True print(Sizes[name_1].value > Sizes[name_2].value)
This is useful when you don't know the name of the enum member ahead of time (because it's read from a file or fetched from an API).

An alternative approach is to extend from the OrderedEnum class from the official docs.

main.py
from enum import Enum class OrderedEnum(Enum): def __ge__(self, other): if self.__class__ is other.__class__: return self.value >= other.value return NotImplemented def __gt__(self, other): if self.__class__ is other.__class__: return self.value > other.value return NotImplemented def __le__(self, other): if self.__class__ is other.__class__: return self.value <= other.value return NotImplemented def __lt__(self, other): if self.__class__ is other.__class__: return self.value < other.value return NotImplemented # class Sizes(OrderedEnum): class Sizes(OrderedEnum): SMALL = 1 MEDIUM = 2 LARGE = 3 # 👇️ True print(Sizes.LARGE.value > Sizes.MEDIUM.value) # 👇️ True print(Sizes.MEDIUM.value < Sizes.LARGE.value) # 👇️ False print(Sizes.SMALL.value == Sizes.LARGE.value)

The OrderedEnum class example from the official docs is the recommended way to compare enums (if you don't consider accessing the value attribute enum comparison).

Note that the class is not exported from the enum module, so we have to copy and paste it in order to use it.

The class implements the comparison methods, so we don't have to.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.