I have a need to add listeners to models who inherit from a mixin, and I want the mixin to have abstract methods that the overriding classes must implement to follow the mixin spec, like so:
from abc import ABC, abstractmethod from app import db from sqlalchemy.orm import declarative_mixin @declarative_mixin class FooMixin(ABC): @abstractmethod def must_implement(self): raise NotImplementedError class A(db.Model, FooMixin): id = db.Column(db.Integer, primary_key=True) ... @sqlalchemy.event.listens_for(Foo, "update", propagate=True) def foo_update_listener(mapper, connection, object): object.must_implement()
This way I would create a dependency on all db models that inherit the FooMixin to also have the
must_implement() method, allowing me to be sure that it’s available in the listener code.
Or is there a better way of ensuring this? I guess the FooMixin isn’t really a Mixin any longer, if it requires inheriting classes to actually implement methods from it..
Source: Python Questions