supermethod shortcut

David Fraser davidf at sjsoft.com
Wed May 26 07:21:47 EDT 2004


Hi

I was recently thinking about the awkwardness I find in using the super 
method to call a superclass's function.

The majority of the time I use super in the following way:

class Y(X):
   def some_method(self, arg1, arg2):
     do_something(arg1)
     arg2 += 1
     super(Y, self).some_method(arg1, arg2)

The whole super(Y, self).some_method seems an awkward way to say "call 
the superclass's version of this function".

So I defined a function that looks up the calling function name in the 
stack frame and calls super on the self attribute, and returns the 
function name:

import sys

def supermethod(currentclass):
   callingframe = sys._getframe().f_back
   functionname = callingframe.f_code.co_name
   self = callingframe.f_locals["self"]
   superobject = super(currentclass, self)
   return getattr(superobject, functionname)

This then reduces the above to supermethod(Y)(arg1, arg2)

Of course explicit is better than implicit and so maybe not looking up 
self is better:

import sys

def supermethod(currentclass, self):
   callingframe = sys._getframe().f_back
   functionname = callingframe.f_code.co_name
   superobject = super(currentclass, self)
   return getattr(superobject, functionname)

This still means you call supermethod(Y, self)(arg1, arg2) instead of 
super(Y, self).functionname(arg1, arg2)

Anyway I just wondered if others would find this interesting / useful / 
material for a flame war :-)

David



More information about the Python-list mailing list