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

2 Answers 2

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})
Sign up to request clarification or add additional context in comments.

Comments

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'>]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.