Defining Abstract Method in SQLAlchemy Base Class
From http://docs.sqlalchemy.org/en/improve_toc/orm/extensions/declarative/mixins.html#augmenting-the-base I see that you can define methods and attributes in the base class.
I would like to make sure all child classes implement a specific method. However, trying to define an abstract method like this:
import abc
from sqlalchemy.ext.declarative import declarative_base
class Base(metaclass=abc.ABCMeta):
@abc.abstractmethod
def implement_me(self):
pass
Base = declarative_base(cls=Base)
class Child(Base):
__tablename__ = 'child'
I am getting the error TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases
I tried to find some documentation or examples to help me, but came up with a short one.
source to share
It looks like you can pass the metaclass to declarative_base
. Default Metaclass - DeclarativeMeta
- So I think the key would be to create a new metaclass which is a mixin of abc.ABCMeta
and DeclarativeMeta
:
import abc
from sqlalchemy.ext.declarative import declarative_base, DeclarativeMeta
class DeclarativeABCMeta(DeclarativeMeta, abc.ABCMeta):
pass
class Base(declarative_base(metaclass=DeclarativeABCMeta)):
__abstract__ = True
@abc.abstractmethod
def implement_me(self):
"""Canhaz override?"""
* Not verified
source to share