Why does super() require the class as the first argument?

Nick Coghlan ncoghlan at iinet.net.au
Fri Feb 4 08:18:32 EST 2005


Kevin Smith wrote:
> I can create a super() that does this as follows:
> 
> _super = super
> def super(obj, cls=None):
>     if cls is None:
>         return _super(type(obj), obj)
>     return super(cls, obj)
> 
> I guess I'm just not sure why it wasn't done that way in the first place.
> 

Because it doesn't work. As Chris pointed out, it leads to infinite recursion:

Py> class A(object):
...   def blow_the_stack(self):
...     print "Well, not yet"
...
Py> class B(A):
...   def blow_the_stack(self):
...     print "Perhaps here"
...     super(type(self), self).blow_the_stack()
...
Py> class C(B):
...   pass
...
Py> A().blow_the_stack()
Well, not yet
Py> B().blow_the_stack()
Perhaps here
Well, not yet
Py> C().blow_the_stack()
Perhaps here
<infinite recursion traceback snipped>
   File "<stdin>", line 4, in blow_the_stack
RuntimeError: maximum recursion depth exceeded

Basically, the first argument to super() says "find this type in the supplied 
objects method resolution order, and then move on to the next type in the 
order". Getting this wrong (e.g. by providing a type earlier in the MRO, as 
B.blow_the_stack does by providing type(C()) above) is what leads to the 
infinite recursion.

It *is* possible to eliminate the explicit class argument, but it takes a bit 
(*cough*) of work:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/286195

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at email.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://boredomandlaziness.skystorm.net



More information about the Python-list mailing list