51

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.

nowox
  • 25,978
  • 39
  • 143
  • 293
  • 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! – Nhor Nov 13 '15 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) – nowox Nov 13 '15 at 10:08

1 Answers1

98

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>]
awesoon
  • 32,469
  • 11
  • 74
  • 99
  • 1
    I wish we could do something like `class MyEnum(IntEnum): _list = ["A", "B", "C"]` – PascalVKooten Nov 12 '17 at 21:34
  • 1
    @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. https://repl.it/@altendky/SevereGiftedDuckbillcat – altendky Nov 15 '17 at 16:27
  • 1
    https://stackoverflow.com/questions/28126314/adding-members-to-python-enums/35899963 – awesoon Apr 04 '20 at 16:35
  • Is there a way to inject also a type dynamically, for example `int` to produce `IntEnum`? – Eduardo Pignatelli Jul 06 '23 at 09:25