Defining an abstract method in a SQLAlchemy base class

旧街凉风 提交于 2021-02-05 05:30:05

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/30402024/defining-an-abstract-method-in-a-sqlalchemy-base-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!