Is it possible extend enum during creation? Example:
class MyEnum(enum.StrEnum):
ID = "id"
NAME = "NAME
And I need that after creating this enum contains the next fields:
ID = "id"
NAME = "name"
ID_DESC = "-id"
NAME_DESC = "-name"
I need this to create custom ordering enum for FastAPI project
Now I have the next way to create new enum
NewEnum = enum.StrEnum(
f"{name.title()}OrderingEnum",
[
(
f"{ordering_field.upper()}_DESC"
if ordering_field.startswith("-")
else ordering_field.upper(),
ordering_field,
)
for ordering_field in itertools.chain(
values,
[f"-{field}" for field in values],
)
],
)
But I need do this automatically, because each module with model have similar enum. Maybe this is possible to solve my problem using MetaClass for my enum class, or override __new__ method, but I didn't find working solution yet
Enhancing the
__new__ofEnumType(used to beEnumMetaand still has that as an alias) will do the job:and in use:
This answer currently uses the private
_EnumDictand its_member_namesattribute, but they'll be public in 3.13.Disclosure: I am the author of the Python stdlib
Enum, theenum34backport, and the Advanced Enumeration (aenum) library.