Skip to content

Instantly share code, notes, and snippets.

@meta-ks
Created July 24, 2023 03:59
Show Gist options
  • Save meta-ks/083fa6daec57175cb2d65f35bae39a17 to your computer and use it in GitHub Desktop.
Save meta-ks/083fa6daec57175cb2d65f35bae39a17 to your computer and use it in GitHub Desktop.
Ordered String Enum. The comparison has been overloaded with .index_value instead of existing .value
from enum import Enum
#Inspired by: https://bobbyhadz.com/blog/python-compare-string-with-enum
# and https://stackoverflow.com/questions/76236985/how-to-compare-string-enums-in-python
class OrderedStrEnum(str, Enum):
def __ge__(self, other):
if self.__class__ is other.__class__:
return self._index() >= other._index()
return NotImplemented
def __gt__(self, other):
if self.__class__ is other.__class__:
return self._index() > other._index()
return NotImplemented
def __le__(self, other):
if self.__class__ is other.__class__:
return self._index() <= other._index()
return NotImplemented
def __lt__(self, other):
if self.__class__ is other.__class__:
return self._index() < other._index()
return NotImplemented
def _index(self):
return list(self.__class__).index(self)
class OrderState(OrderedStrEnum):
CREATED = 'CREATED'
SUBMITTED = 'SUBMITTED'
PUT_ORDER_REQ_RECEIVED = 'PUT ORDER REQ RECEIVED'
VALIDATION_PENDING = 'VALIDATION PENDING'
OPEN_PENDING = 'OPEN PENDING'
REJECTED = 'REJECTED'
TRIGGER_PENDING = 'TRIGGER PENDING'
OPEN = 'OPEN'
# In [4]: OrderState.OPEN.value == 'OPEN'
# Out[4]: True
# In [5]: OrderState.OPEN_PENDING < OrderState.VALIDATION_PENDING
# Out[5]: False
# In [7]: OrderState.OPEN_PENDING.value < OrderState.VALIDATION_PENDING.value
# Out[7]: True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment