Reputation: 1799
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'd like to make sure that all the child classes implement a particular method. However, in trying to define an abstract method like so:
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 get 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 short.
Upvotes: 9
Views: 3808
Reputation: 310049
It looks like you can pass a metaclass to declarative_base
. The default metaclass is DeclarativeMeta
-- So, I think the key would be to create a new metaclass that 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?"""
*Untested
Upvotes: 13