Resolving metaclass conflicts

Yves Dorfsman picture Yves Dorfsman · Jun 30, 2012 · Viewed 62.5k times · Source

I need to create a class that uses a different base class depending on some condition. With some classes I get the infamous:

TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases

One example is sqlite3, here is a short example you can even use in the interpreter:

>>> import sqlite3
>>> x = type('x', (sqlite3,), {})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases

Answer

Michael picture Michael · Dec 1, 2012

Instead of using the receipe as mentioned by jdi, you can directly use:

class M_C(M_A, M_B):
    pass

class C(A, B):
    __metaclass__ = M_C