I had to create a extra mapping in an Enum to save additional information, like an verbose description of each enum case, but without losing the Enum classes properties. Ex:
class MyEnumBase:
description = {
1: 'Description 1',
2: 'This is anover description',
3: 'la la la',
}
class MyEnum(MyEnumBase, Enum):
First = 1
Second = 2
Third = 3
So I access it like this:
MyEnum.description[3] == 'la la la'
.
How can I extend the Enum class so in the cases where the descriptions are the same as the enum name, it would populate this dictionary with the names of the fields?
Eg:
class MyAnotherEnum(CustomEnumBase):
aaa = 1
bbb = 2
ccc = 3
so that MyAnotherEnum.description[3] == 'ccc'
, auto generating the description
property for every Enum created from this CustomEnumBase
.
I tried to extend the Enum
class but all the things I've tried failed. I was thinking something like this:
class CustomEnumBase:
@property
def names(cls):
return {
id:member.name
for id, member in cls._value2member_map_.items()
}
There are 2 restrictions:
It should extend python Enum classes, so the places where an Enum is expected it behaves correctly. There are some third party codes that rely on this.
It should keep access to the description as a mapping, as this protocol is already expected and used in the codebase. So changing it to
MyAnotherEnum.description()[id]
is not viable, as it expect a mapping (dict), not a function.