I am declaring a class in Python in which one instance attribute would be restricted in its value to Enum members. I achieve this with the pydantic
package. As the enum members are provided by the user in a list enum_members
, inside a config-file, I need a dynamical approach to create the Enum
and cannot hardcode its members. I understand that the right approach to do that is:
from enum import Enum
MyEnum = Enum('MyEnum', enum_members)
However, this does not only define an Enum class called MyEnum
, it also creates an instance of that class, that is also called MyEnum
. Is there a way to create the class alone?
If I write:
Enum('MyEnum', enum_members)
I get no error, but I no longer can use MyEnum
.
Surprisingly, I can also write:
MyEnumNew = Enum('MyEnum', enum_members)
and I can use MyEnumNew
.
What is the purpose of the string argument in Enum(...)
?
However, this does not only define an Enum class called MyEnum, it also creates an instance of that class, that is also called MyEnum.
This is untrue. It just creates the class.
I get no error, but I no longer can use MyEnum.
Because you just called a function and didn't assign the result. Same as you'd just call input("enter a thing")
, and didn't assign the result.
What is the purpose of the string argument in Enum(...)?
To name the enum, because there's no way for it to otherwise have a descriptive name. The enum's intrinsic name doesn't need to be the same as the name you assign it to, as you'd noticed.
>>> E = Enum("Foople", [])
>>> E.__name__
'Foople'
Surprisingly, I can also write: ...
Yes, and you can do that with classes too.
>>> class X:
... pass
...
>>> Y = X
>>> Y
<class '__main__.X'>
>>>
For the record, the "function form" of class ...
is type()
:
>>> Z = type('Foople', (), {})
>>> Z
<class '__main__.Foople'>
>>>