1

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

edmamerto
  • 7,605
  • 11
  • 42
  • 66

2 Answers2

1
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'>]
Ethan Furman
  • 63,992
  • 20
  • 159
  • 237
1

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})
Tom
  • 8,310
  • 2
  • 16
  • 36