Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate an enum class from a list in python

Tags:

python-3.x

Suppose I want to create the following enum class:

from enum import Enum, unique

@unique
class Indication(Enum):
    Fruit1 = 'apple'
    Fruit2 = 'orange'
    Fruit3 = 'banana'

I want to create it from a python list, i.e.,

Listoffruits = [('Fruit1', 'apple'),  ('Fruit2', 'orange'), ('Fruit3',  'banana')]

How can this be done effectively?

like image 676
Nithin Govindarajan Avatar asked Oct 26 '25 08:10

Nithin Govindarajan


2 Answers

Use the Functional API if you want to dynamically define an Enum:

import enum

Listoffruits = [('Fruit1', 'apple'),  ('Fruit2', 'orange'), ('Fruit3',  'banana')]

Indication = enum.Enum('Indication', dict(Listoffruits))

You can use string formatting to "generate" the Python code:

def generate_enum(enumClass, enumDict):
    """
    Generates python code for an Enum
    """

    enum_template = """
@unique
class {enumClass}(Enum)
{enumBody}
"""

    enumBody = '\n'.join([f"    {name} = '{value}'" for (name,value) in enumDict.items()])

    return enum_template.format(enumClass=enumClass,enumBody=enumBody)

print(generate_enum('Indication',dict(Listoffruits)))

The generated code will be:

@unique
class Indication(Enum)
    Fruit1 = 'apple'
    Fruit2 = 'orange'
    Fruit3 = 'banana'
like image 67
Ali Rathore Avatar answered Oct 28 '25 23:10

Ali Rathore


Enum docs mentions a functional API. So you can just do:

from enum import Enum
Indication = Enum('Indication', dict(Listoffruits))

Proof:

>>> list(Indication)
[<Indication.Fruit1: 'apple'>,
 <Indication.Fruit2: 'orange'>,
 <Indication.Fruit3: 'banana'>]

As a matter of exploring Python, you can consider how this hack works (it does):

from enum import Enum, unique

def inject_items(d, items):
    for k, v in items:
        d[k] = v

@unique
class Indication(Enum):
    inject_items(locals(), Listoffruits)

But that's just for educational purposes. I'd use Enum's functional API for you purpose.

like image 43
thorwhalen Avatar answered Oct 28 '25 23:10

thorwhalen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!