67

I would like to create an enum type at runtime by reading the values in a YAML file. So I have this:

# Fetch the values
v = {'foo':42, 'bar':24}

# Create the enum
e = type('Enum', (), v)

Is there a proper way to do it? I feel calling type is not a very neat solution.

3
  • I'm not quite sure why is your Enum having e.foo and e.bar attributes with such weird values assigned. It's not Enum at all! Commented Nov 13, 2015 at 10:05
  • 2
    @Nhor what is then? I am writing a wrapper from a C library where there is some enums like typedef enum {soda = 3423, flower = 5827, water = 999} articles_t; (this is an example obviously) Commented Nov 13, 2015 at 10:08
  • Google brought me here, so tagging my answer on the related question: stackoverflow.com/a/78957622/1267156 Commented Sep 6, 2024 at 14:38

1 Answer 1

123

You can create new enum type using Enum functional API:

In [1]: import enum

In [2]: DynamicEnum = enum.Enum('DynamicEnum', {'foo':42, 'bar':24})

In [3]: type(DynamicEnum)
Out[3]: enum.EnumMeta

In [4]: DynamicEnum.foo
Out[4]: <DynamicEnum.foo: 42>

In [5]: DynamicEnum.bar
Out[5]: <DynamicEnum.bar: 24>

In [6]: list(DynamicEnum)
Out[6]: [<DynamicEnum.foo: 42>, <DynamicEnum.bar: 24>]
Sign up to request clarification or add additional context in comments.

5 Comments

I wish we could do something like class MyEnum(IntEnum): _list = ["A", "B", "C"]
@PascalvKooten how about creating the dict like {name: index for index, name in enumerate(the_list)}. It doesn't work for the dynamic (haven't looked into it) but for static it will autonumber. repl.it/@altendky/SevereGiftedDuckbillcat
Is there a way to inject also a type dynamically, for example int to produce IntEnum?
@EduardoPignatelli I know it's almost a year and a half later but you can do something like an IntEnum or a StrEnum using my solution on the linked question: stackoverflow.com/a/78957622/1267156

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.