Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I dynamically add mixins as base classes without getting MRO errors?
    text
    copied!<p>Say I have a class <code>A</code>, <code>B</code> and <code>C</code>.</p> <p>Class <code>A</code> and <code>B</code> are both mixin classes for Class <code>C</code>.</p> <pre><code>class A( object ): pass class B( object ): pass class C( object, A, B ): pass </code></pre> <p>This will not work when instantiating class C. I would have to remove <code>object</code> from class C to make it work. (Else you'll get MRO problems).</p> <blockquote> <p>TypeError: Error when calling the metaclass bases<br> Cannot create a consistent method resolution<br> order (MRO) for bases B, object, A</p> </blockquote> <p>However, my case is a bit more complicated. In my case class <code>C</code> is a <em>server</em> where <code>A</code> and <code>B</code> will be plugins that are loaded on startup. These are residing in their own folder.</p> <p>I also have a Class named <code>Cfactory</code>. In Cfactory I have a <code>__new__</code> method that will create a fully functional object C. In the <code>__new__</code> method I <em>search</em> for plugins, load them using <code>__import__</code>, and then assign them to <code>C.__bases__ += (loadedClassTypeGoesHere, )</code></p> <p>So the following is a possibility: (made it quite abstract)</p> <pre><code>class A( object ): def __init__( self ): pass def printA( self ): print "A" class B( object ): def __init__( self ): pass def printB( self ): print "B" class C( object ): def __init__( self ): pass class Cfactory( object ): def __new__( cls ): C.__bases__ += ( A, ) C.__bases__ += ( B, ) return C() </code></pre> <p>This again will not work, and will give the MRO errors again: </p> <blockquote> <p>TypeError: Cannot create a consistent method resolution<br> order (MRO) for bases object, A</p> </blockquote> <p>An easy fix for this is removing the <code>object</code> baseclass from <code>A</code> and <code>B</code>. However this will make them old-style objects which should be avoided when these plugins are being run stand-alone (which should be possible, UnitTest wise)</p> <p>Another easy fix is removing <code>object</code> from <code>C</code> but this will also make it an old-style class and <code>C.__bases__</code> will be unavailable thus I can't add extra objects to the base of <code>C</code></p> <p>What would be a good architectural solution for this and how would you do something like this? For now I can live with old-style classes for the plugins themselves. But I rather not use them.</p>
 

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