Skip to content

Instantly share code, notes, and snippets.

@antonagestam
Created May 6, 2019 13:34
Show Gist options
  • Select an option

  • Save antonagestam/22f0bcd5132cb91a8f3a9bee9c5cbd30 to your computer and use it in GitHub Desktop.

Select an option

Save antonagestam/22f0bcd5132cb91a8f3a9bee9c5cbd30 to your computer and use it in GitHub Desktop.
SQLAlchemy typed IntegerEnum
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