简体   繁体   中英

Defining an abstract method in a 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'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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM