I\'m reading about sqlalchemy and I saw following code:
employees_table = Table(\'employees\', metadata,
Column(\'employee_id\', Integer, primary_key=Tru
I'm not really knowledgeable in SQLAlchemy but this approach by Paulo seemed much simpler to me.
I didn't need user-friendly descriptions, so I went with it.
Quoting Paulo (I hope he doesn't mind my reposting it here):
Python’s
namedtuple
collection to the rescue. As the name implies, anamedtuple
is a tuple with each item having a name. Like an ordinary tuple, the items are immutable. Unlike an ordinary tuple, an item’s value can be accessed through its name using the dot notation.Here is a utility function for creating a
namedtuple
:from collections import namedtuple def create_named_tuple(*values): return namedtuple('NamedTuple', values)(*values)
The
*
before the values variable is for “unpacking” the items of the list so that each item is passed as an individual argument to the function.To create a
namedtuple
, just invoke the above function with the needed values:>>> project_version = create_named_tuple('alpha', 'beta', 'prod') NamedTuple(alpha='alpha', beta='beta', prod='prod')
We can now use the
project_version
namedtuple to specify the values of the version field.class Project(Base): ... version = Column(Enum(*project_version._asdict().values(), name='projects_version')) ...
This works great for me and is so much simpler than the other solutions that I previously found.