Dynamically create an enum with custom values in Python?

22,488

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>]
Share:
22,488
nowox
Author by

nowox

Software and Electronic Engineer specialized in MotionControl applications.

Updated on July 16, 2022

Comments

  • nowox
    nowox almost 2 years

    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.

  • PascalVKooten
    PascalVKooten over 6 years
    I wish we could do something like class MyEnum(IntEnum): _list = ["A", "B", "C"]
  • altendky
    altendky over 6 years
    @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
  • awesoon
    awesoon about 4 years