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.
CodePudding user response:
The Enum
class can be called to dynamically create a new Enum
type. This will also work for subclasses of Enum
MyEnum = FriendlyEnum('MyEnum', {'foo': 1, 'bar': 2})
MyEnum.foo.hello()
CodePudding user response:
An explanation of why it's not working: EnumMeta
is expecting the class dictionary (classdict
above) to be an instance of enum._EnumDict
, but what you gave it was a normal dict (hence no _member_names
attribute).
Using type
to directly create an enum
is not supported -- use the method outlined by Iain Shelvington instead.