Created
October 5, 2016 20:04
-
-
Save guyarad/119da9ded795e9c471b5c0fae88bed5a to your computer and use it in GitHub Desktop.
Wrapper for Python classic enum to be used as SQL Alchemy enum type
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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