Resolving metaclass conflicts

后端 未结 6 1227
时光取名叫无心
时光取名叫无心 2020-12-03 09:25

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: t         


        
6条回答
  •  一整个雨季
    2020-12-03 10:16

    Your example using sqlite3 is invalid because it is a module and not a class. I have also encountered this issue.

    Heres your problem: The base class has a metaclass that is not the same type as the subclass. That is why you get a TypeError.

    I used a variation of this activestate snippet using noconflict.py. The snippet needs to be reworked as it is not python 3.x compatible. Regardless, it should give you a general idea.

    Problem snippet

    class M_A(type):
        pass
    class M_B(type):
        pass
    class A(object):
        __metaclass__=M_A
    class B(object):
        __metaclass__=M_B
    class C(A,B):
        pass
    
    #Traceback (most recent call last):
    #  File "", line 1, in ?
    #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
    #
    

    The code recipe properly resolves the metaclasses for you.

提交回复
热议问题