Updated blog post on how to use super()

Chris Torek nospam at torek.net
Wed Jun 1 13:43:19 EDT 2011


Summary: super(cls, data) in a method gets you the "next" handler
for a given class "cls" and an instance "data" that has derived
from that class at some point.  In Python 2 you must spell out the
names of the class and instance (normally "self") explicitly, while
Python 3 grabs, at compile time, the class from the lexically
enclosing class, and the instance from the first argument of the
method that invokes "super".

The "next" handler depends on the instance's __mro__.  If all
your classes use at most single inheritance, the "next" handler
in class Cls1 is easy to predict:

    class Cls1(Cls2):

Any instance of Cls1 always has Cls2 as its "next", so:

        def method(self, arg1, arg2):
            ...
            Cls2.method(self, arg1_mutated, arg2_mutated)
            ...

works fine.  But if you use multiple inheritance, the next method
is much harder to predict.  If you have a working "super", you
can use:

            super().method(self, arg1_mutated, arg2_mutated)

and it will find the correct "next method" in all cases.

In article <is5qd7$t5b$1 at speranza.aioe.org>
Billy Mays  <noway at nohow.com> wrote:
>What it does is clear to me, but why is it interesting or special isn't. 
>  This looks like a small feature that would be useful in a handful of 
>cases.

Indeed: it is useful when you have multiple inheritance, which for
most programmers, is a "handful of cases".

However, provided you *have* the Py3k super() in the first place,
it is also trivial and obviously-correct to write:

        super().method(...)

whereas writing:

        NextClass.method(...)

requires going up to the class definition to make sure that
"NextClass" is indeed the next class, and hence -- while usually
no more difficult to write -- less obviously-correct.

Moreover, if you write the easy-to-write obviously-correct
"super().method", *your* class may now be ready for someone
else to use in a multiple-inheritance (MI) situation.  If you type
in the not-as-obviously-correct "NextClass.method", *your* class
is definitely *not* ready for someone else to use in that MI
situation.

(I say "may" be ready for MI, because being "fully MI ready" requires
several other code discipline steps.  The point of super() -- at
least when implemented nicely, as in Py3k -- is that it makes it
easy -- one might even say "super easy" :-) -- to write your code
such that it is obviously correct, and also MI-friendly.)
-- 
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W)  +1 801 277 2603
email: gmail (figure it out)      http://web.torek.net/torek/index.html



More information about the Python-list mailing list