Python how to list an array and make them an Enum

Viewed 99

So I'm trying to achieve something like this

from enum import Enum

tabulate_formats = ['fancy_grid', 'fancy_outline', 'github', 'grid']

class TableFormat(str, Enum):
    for item in tabulate_formats:
        exec(f"{item} = '{item}'")

Though i get this error

Traceback (most recent call last):
  File "/app/src/main.py", line 25, in <module>
    class TableFormat(str, Enum):
  File "/app/src/main.py", line 26, in TableFormat
    for item in tabulate_formats:
  File "/usr/local/lib/python3.6/enum.py", line 92, in __setitem__
    raise TypeError('Attempted to reuse key: %r' % key)
TypeError: Attempted to reuse key: 'item'

How do I properly assign them into the class

2 Answers
class StrEnum(str, Enum):
    @staticmethod
    def _generate_next_value_(name, *args):
        return name

TableFormat = StrEnum('TableFormat', tabulate_formats)

and

>>> list(TableFormat)
[<TableFormat.fancy_grid: 'fancy_grid'>, <TableFormat.fancy_outline: 'fancy_outline'>, <TableFormat.github: 'github'>, <TableFormat.grid: 'grid'>]

Not sure if this would also be acceptable, but based on turning a dict into an Enum, you could do:

TableFormat = Enum('TableFormat', {i:i for i in tabulate_formats})
Related