in search of a nicer super ...

Michele Simionato michele.simionato at poste.it
Tue May 18 07:50:34 EDT 2004


Here is an idea for a nicer syntax in cooperative method calls,
which is not based on Guido's "autosuper" example. This is just a 
hack, waiting for a nicer "super" built-in ...

Here is example of usage:

from cooperative import Cooperative

class B(Cooperative):
    def print_(self):
        print "B",

class C(B):
    def print_(self, super):
        super.print_() # shortcut for super(C,self).print_()
        print "C",

class D(C):
    def print_(self, super):
        super.print_() # shortcut for super(D,self).print_()
        print "D",

D().print_() # prints BCD

Let me call "cooperative methods" methods with a second argument 
called "super": then super.method(*args, **kw) acts as a shortcut 
for super(cls,self).method(*args, **kw). This avoids the redundant
repetition of the class in the super object, a thing I always loathed :)

Here is the "cooperative" module:

$ cat cooperative.py
import inspect

def second_arg(func):
    args = inspect.getargspec(func)[0]
    if len(args) >= 2: return args[1]

class _Cooperative(type):
    def __init__(cls,name,bases,dic):
        for n,func in dic.iteritems():
            if inspect.isfunction(func) and second_arg(func) == "super":
                setattr(cls, n, cls.wrap(func))
    def wrap(cls, func):
        return lambda self, *args, **kw : \
               func(self, super(cls, self), *args, **kw)

class Cooperative:
    __metaclass__ = _Cooperative

I could make it to work for staticmethods and classmethods, but
I didn't bothered since I wanted to keep the cooperative module
under the twenty lines.

Just my 0.02c,


                          Michele Simionato



More information about the Python-list mailing list