6

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.

1 Answer 1

14

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.

Sign up to request clarification or add additional context in comments.

4 Comments

nice - thank you. In addition, in order to get strings for the enum values as in the original, this does the trick: myEnumStrings = ( (x,x) for x in ('RED', 'GREEN', 'BLUE')).
How do I compare string values with the string enums with the above declaration? Example: 'RED'== MyEnumType.RED @fundamental @will-da-silva
Figured out. The way to do the comparison 'RED'== MyEnumType.RED: MyEnumType = Enum('MyEnumType', myEnumStrings, type=str)
@thegreatcoder You can also use enum.StrEnum without the type argument instead of enum.Enum to achieve this in Python 3.11+

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.