Strange metaclass behaviour

Christian Eder eder at tttech.com
Thu Mar 23 11:21:01 CET 2006


Hi,

I think I have discovered a problem in context of
metaclasses and multiple inheritance in python 2.4,
which I could finally reduce to a simple example:

Look at following code:

class M_A (type) :

     def __new__ (meta, name, bases, dict) :
        print "M.__new__", meta, name, bases
        return super (M_A, meta).__new__ (meta, name, bases, dict)

class M_B (M_A) : pass

class A (object) : __metaclass__ = M_A

class B (object) : __metaclass__ = M_B

class D (A, B) : pass


One would expect that either
1) D inherits the metaclass M_A from A
2) or python raises the well known "Metatype conflict among bases"
error

Instead, if you run this code, you get the following output:

M.__new__ <class '__main__.M_A'> A (<type 'object'>,)
M.__new__ <class '__main__.M_B'> B (<type 'object'>,)
M.__new__ <class '__main__.M_A'> D (<class '__main__.A'>, <class
'__main__.B'>)
M.__new__ <class '__main__.M_B'> D (<class '__main__.A'>, <class
'__main__.B'>)

This means that when class D gets defined, the __new__ from M_A
get executed twice (first from M_A, then from M_B), which should not happen.
This suggests that either
1) cooperative supercalls do not work here
2) the metaclass of EACH of the bases of D does it's work independently
when D is defined.

Does anyone have a detailed explanation here ?
Is this problem already known ?

regards
chris



More information about the Python-list mailing list