Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Wrapper for Python classic enum to be used as SQL Alchemy enum type
# DEFINITION
# ==========
class PythonEnumWrapper(sa.Enum):
def __init__(self, cls):
"""
Initializes a new ``PythonEnumWrapper`` to be used as ``sqlalchemy.Enum``
Args:
cls: a classic enumeration type
"""
enums = map(operator.attrgetter('name'), cls)
super(PythonEnumWrapper, self).__init__(*enums, name=cls.__name__)
# USAGE
# =====
# Given the following enum definition:
class MyClassicEnum(enum.Enum):
enum_item_1 = 0
enum_item_2 = 1
# in your ORM class put the following:
class MyTable(Base):
...
my_typed_column = Column(PythonEnumWrapper(MyClassicEnum))
# OUTPUT
# ======
# this will produce something like that:
"""
2016-10-05 22:58:13,395 INFO sqlalchemy.engine.base.Engine {'typname': u'MyClassicEnum'}
2016-10-05 22:58:13,396 INFO sqlalchemy.engine.base.Engine CREATE TYPE "MyClassicEnum" AS ENUM ('enum_item_1', 'enum_item_2')
2016-10-05 22:58:13,405 INFO sqlalchemy.engine.base.Engine
CREATE TABLE my_table (
id SERIAL NOT NULL,
my_typed_column "MyClassicEnum",
PRIMARY KEY (id)
)
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.