Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resolving metaclass conflicts

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 
like image 764
Yves Dorfsman Avatar asked Jun 30 '12 17:06

Yves Dorfsman


People also ask

What is metaclass conflict in Python?

TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass #of the metaclasses of all its bases. Solution snippet from noconflict import classmaker class C(A,B): __metaclass__=classmaker() print C #<class 'C'>

What is the concept of a metaclass?

A metaclass in Python is a class of a class that defines how a class behaves. A class is itself an instance of a metaclass. A class in Python defines how the instance of the class will behave. In order to understand metaclasses well, one needs to have prior experience working with Python classes.

What is the purpose of metaclass?

Custom metaclasses The main purpose of a metaclass is to change the class automatically, when it's created. You usually do this for APIs, where you want to create classes matching the current context.

Is object a metaclass?

In general, the type of any new-style class is type . type is a metaclass, of which classes are instances. Just as an ordinary object is an instance of a class, any new-style class in Python, and thus any class in Python 3, is an instance of the type metaclass.


1 Answers

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

class M_C(M_A, M_B):     pass  class C(A, B):     __metaclass__ = M_C 
like image 75
Michael Avatar answered Oct 01 '22 13:10

Michael