[issue1294232] Error in metaclass search order

Daniel Urban report at bugs.python.org
Sun Aug 8 09:56:37 CEST 2010


Daniel Urban <urban.dani+py at gmail.com> added the comment:

I think the situation is a bit more complicated. Here is the example described by Pedro Werneck (this is py3k, but its essentially the same in 2.x):

>>> class M_A(type):
...     def __new__(mcls, name, bases, ns):
...             print('M_A.__new__')
...             return super().__new__(mcls, name, bases, ns)
...
>>> class A(metaclass=M_A): pass
...
M_A.__new__
>>>
>>>
>>> class M_B(M_A):
...     def __new__(mcls, name, bases, ns):
...             print('M_B.__new__')
...             return super().__new__(mcls, name, bases, ns)
...
>>> class B(A, metaclass=M_B): pass
...
M_B.__new__
M_A.__new__
>>>
>>>
>>> class C(B, metaclass=M_A): pass
...
M_A.__new__
M_B.__new__
M_A.__new__
>>> 

As it is clear from the last three lines, the given metaclass (M_A) to C is not ignored. It is actually called (and produces the 'M_A.__new__' output line). Then M_A.__new__ calls type.__new__ (with super()). type.__new__ then searches the bases of C, find the metaclass of B, M_B, and calls its __new__. M_B.__new__ then prints the line 'M_B.__new__', then calls M_A.__new__ again (with super()). This produces the last line, 'M_A.__new__'. So the trick is in type.__new__.

----------
nosy: +durban

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue1294232>
_______________________________________


More information about the Python-bugs-list mailing list