I am trying to create an Enum class dynamically, using type(name, base, dict).
from enum import Enum
class FriendlyEnum(Enum):
def hello(self):
print(self.name + ' says hello!')
The normal way works fine:
class MyEnum(FriendlyEnum):
foo = 1
bar = 2
MyEnum.foo.hello()
# ->
foo says hello!
But if I try dynamically:
MyEnum = type('MyEnum',
(FriendlyEnum,),
{'foo':1,'bar':2}
)
MyEnum.foo.hello()
# ->
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/enum.py", line 146, in __new__
enum_members = {k: classdict[k] for k in classdict._member_names}
AttributeError: 'dict' object has no attribute '_member_names'
Any suggestions?
It might be useful for testing the methods of a parent Enum class, dynamically creating new Enum classes with different attributes and same inherited methods.