Search code examples
pythonclassarchitecturemethod-resolution-order

How do I dynamically add mixins as base classes without getting MRO errors?


Say I have a class A, B and C.

Class A and B are both mixin classes for Class C.

class A( object ):
    pass
class B( object ):
    pass
class C( object, A, B ):
    pass

This will not work when instantiating class C. I would have to remove object from class C to make it work. (Else you'll get MRO problems).

TypeError: Error when calling the metaclass bases
Cannot create a consistent method resolution
order (MRO) for bases B, object, A

However, my case is a bit more complicated. In my case class C is a server where A and B will be plugins that are loaded on startup. These are residing in their own folder.

I also have a Class named Cfactory. In Cfactory I have a __new__ method that will create a fully functional object C. In the __new__ method I search for plugins, load them using __import__, and then assign them to C.__bases__ += (loadedClassTypeGoesHere, )

So the following is a possibility: (made it quite abstract)

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()

This again will not work, and will give the MRO errors again:

TypeError: Cannot create a consistent method resolution
order (MRO) for bases object, A

An easy fix for this is removing the object baseclass from A and B. 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)

Another easy fix is removing object from C but this will also make it an old-style class and C.__bases__ will be unavailable thus I can't add extra objects to the base of C

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.


Solution

  • Think of it this way -- you want the mixins to override some of the behaviors of object, so they need to be before object in the method resolution order.

    So you need to change the order of the bases:

    class C(A, B, object):
        pass
    

    Due to this bug, you need C not to inherit from object directly to be able to correctly assign to __bases__, and the factory really could just be a function:

    class FakeBase(object):
        pass
    
    class C(FakeBase):
        pass
    
    def c_factory():
        for base in (A, B):
            if base not in C.__bases__:
                C.__bases__ = (base,) + C.__bases__
        return C()