Note that there are some explanatory texts on larger screens.

plurals
  1. POSqlalchemy: avoiding multiple inheritance and having abstract base class
    text
    copied!<p>So I have a bunch of tables using SQLAlchemy that are modelled as objects which inherit from the result to a call to <code>declarative_base()</code>. Ie:</p> <pre><code>Base = declarative_base() class Table1(Base): # __tablename__ &amp; such here class Table2(Base): # __tablename__ &amp; such here </code></pre> <p>Etc. I then wanted to have some common functionality available to each of my DB table classes, <a href="http://docs.sqlalchemy.org/en/latest/orm/extensions/declarative.html#declarative-mixins" rel="noreferrer">the easiest way to do this according to the docs</a> is to just do multiple inheritance:</p> <pre><code>Base = declarative_base() class CommonRoutines(object): @classmethod def somecommonaction(cls): # body here class Table1(CommonRoutines, Base): # __tablename__ &amp; such here class Table2(CommonRoutines, Base): # __tablename__ &amp; such here </code></pre> <p>The thing I don't like about this is A) multiple inheritance in general is a bit icky (gets tricky resolving things like <code>super()</code> calls, etc), B) if I add a new table I have to remember to inherit from both <code>Base</code> and <code>CommonRoutines</code>, and C) really that "CommonRoutines" class "is-a" type of table in a sense. Really what <code>CommonBase</code> is is an abstract base class which defines a set of fields &amp; routines which are common to all tables. Put another way: "its-a" abstract table.</p> <p>So, what I'd like is this:</p> <pre><code>Base = declarative_base() class AbstractTable(Base): __metaclass__ = ABCMeta # make into abstract base class # define common attributes for all tables here, like maybe: id = Column(Integer, primary_key=True) @classmethod def somecommonaction(cls): # body here class Table1(AbstractTable): # __tablename__ &amp; Table1 specific fields here class Table2(AbstractTable): # __tablename__ &amp; Table2 specific fields here </code></pre> <p>But this of course doesn't work, as I then have to A) define a <code>__tablename__</code> for <code>AbstractTable</code>, B) the ABC aspect of things causes all sorts of headaches, and C) have to indicate some sort of DB relationship between <code>AbstractTable</code> and each individual table. </p> <p>So my question: is it possible to achieve this in a reasonable way? Ideally I'd like to enforce:</p> <ul> <li>No multiple inheritance</li> <li><code>CommonBase</code>/<code>AbstractTable</code> be abstract (ie cannot be instantiated)</li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload