Created
May 6, 2019 13:34
-
-
Save antonagestam/22f0bcd5132cb91a8f3a9bee9c5cbd30 to your computer and use it in GitHub Desktop.
SQLAlchemy typed IntegerEnum
This file contains hidden or 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
| from typing import Type, TypeVar | |
| from enum import IntEnum | |
| import sqlalchemy | |
| E = TypeVar('E', bound=IntEnum) | |
| class IntegerEnum(sqlalchemy.types.TypeDecorator): | |
| impl = sqlalchemy.Integer | |
| def __init__(self, enum_type: Type[E], *args, **kwargs): | |
| super().__init__(*args, **kwargs) | |
| self._enum_type = enum_type | |
| def process_bind_param(self, value: E, dialect: str) -> int: | |
| return value.value | |
| def process_result_value(self, value: int, dialect: str) -> E: | |
| return self._enum_type(value) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment