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'
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.
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.
Enums can't have multiple value per name.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With