another super wart

Christian Tanzer tanzer at swing.co.at
Thu Mar 13 02:44:06 EST 2003


mis6 at pitt.edu (Michele Simionato) wrote:

> I have found a very subtle problem (bug?) with super used in conjunction
> with __new__. It does not do what I expect.
(snip)
> How is it possible?? It seems that __new__ is very special and behaves
> in the opposite way of new! (__init__ instead would work as expected).

It isn't a bug, it is a feature. `super` doesn't really have anything
to do with it.

For new-style classes, python handles magic methods differently than
normal methods. For normal methods, python uses the standard attribute
lookup rules, i.e., it first looks in the instance dictionary,
followed by the class dictionary, followed by the bases of the class.

For magic methods, python *ignores* the instance dictionary and goes
directly to the class dictionary. It must do so, because otherwise
metaclasses would not work.

Alex Martelli recently posted a much longer explanation
(Message-id: <b42ev802l51 at enews4.newsguy.com>).

> Discovering this very subtle inconsistency (which I would call a bug
> in the implementation of super) made me loose an afternoon :-(

I also lost a few hours (and gained a few grey hairs) with this
feature. Unfortunately, the only thing to do about it is improve the
documentation.

My personal conclusion was to prefix all metaclass methods with `m_`
(much as I detest such naming conventions in general). Using
`classmethod` instead of defining methods in the metaclass also might
help to keep sanity <wink>.

-- 
Christian Tanzer                                         tanzer at swing.co.at
Glasauergasse 32                                       Tel: +43 1 876 62 36
A-1130 Vienna, Austria                                 Fax: +43 1 877 66 92






More information about the Python-list mailing list