Create an enum class from a list of strings in Python

When I run this

from enum import Enum

class MyEnumType(str, Enum):
    RED   = 'RED'
    BLUE  = 'BLUE'

for x in MyEnumType:

I get the following as expected:


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.


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.