Menu

📰
0

Enums with custom order

Reddit r/learnpython·u/kauwa-biryani·about 1 month ago
#IgT4hsAL
Reading 0:00
15s threshold

Enums with custom order I am trying to implement an StrEnum subclass that serializes like a str but I want objects of this subclass to sort in order of definition, not the str-value which is the default. ``` from enum import Enum, StrEnum from functools import total_ordering @total_ordering class OrderedEnum(Enum): def __lt__(self, other): if self.__class__ is other.__class__: return list(self.__class__).index(self) < list(self.__class__).index(other) return NotImplemented class OrderedStrEnum(OrderedEnum, StrEnum): pass ``` Reason why I did not define __lt__ and total_ordering decoration on OrderedStrEnum directly is because StrEnum inherits from str, so total_ordering will not fill in other comparison methods as they are already present. This seems to work and give me what I want.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.

Read More