Reputation: 133
When I run this
from enum import Enum
class MyEnumType(str, Enum):
RED = 'RED'
BLUE = 'BLUE'
GREEN = 'GREEN'
for x in MyEnumType:
print(x)
I get the following as expected:
MyEnumType.RED
MyEnumType.BLUE
MyEnumType.GREEN
Is it possible to create a class like this from a list or tuple that has been obtained from elsewhere?
Something vaguely similar to this perhaps:
myEnumStrings = ('RED', 'GREEN', 'BLUE')
class MyEnumType(str, Enum):
def __init__(self):
for x in myEnumStrings :
self.setattr(self, x,x)
However, in the same way as in the original, I don't want to have to explicitly instantiate an object.
Upvotes: 6
Views: 6200
Reputation: 7030
You can use the enum functional API for this:
from enum import Enum
myEnumStrings = ('RED', 'GREEN', 'BLUE')
MyEnumType = Enum('MyEnumType', myEnumStrings)
From the docs:
The first argument of the call to Enum is the name of the enumeration.
The second argument is the source of enumeration member names. It can be a whitespace-separated string of names, a sequence of names, a sequence of 2-tuples with key/value pairs, or a mapping (e.g. dictionary) of names to values.
Upvotes: 13