Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I construct an enum.Enum from a dictionary of values?

I'd like to generate some types at runtime from a config file. For simplity, let's assume I already have the data loaded as a python dictionary:

color_values = dict(RED = 1, YELLOW = 2, GREEN = 3)

How can I transform this into the type (using enum)

class Color(enum.Enum):
    RED = 1
    YELLOW = 2
    GREEN = 3

The following doesn't work

def make_enum(name, values):
    return type(name, (enum.Enum,), values)
>>> Color = make_enum('Color', color_values)
AttributeError: 'dict' object has no attribute '_member_names'
like image 309
Eric Avatar asked Nov 15 '17 03:11

Eric


People also ask

Is an enum a dictionary?

Dictionaries store unordered collections of values of the same type, which can be referenced and looked up through a unique identifier (also known as a key). An enumeration defines a common type for a group of related values and enables you to work with those values in a type-safe way within your code.

How do you declare an enum in Python?

Enum is a class in python for creating enumerations, which are a set of symbolic names (members) bound to unique, constant values. The members of an enumeration can be compared by these symbolic anmes, and the enumeration itself can be iterated over.

Can enum have multiple values python?

Enums can't have multiple value per name.


1 Answers

Color = Enum('Color', color_values)

Tada! There's a provided API for that. You can also give it an iterable of name-value pairs, or an iterable of just names (in which case the values will be auto-filled starting from 1), or a whitespace- or comma-separated string of names (which will also auto-fill values).

like image 186
user2357112 supports Monica Avatar answered Sep 21 '22 08:09

user2357112 supports Monica