in search of a nicer super ...

M

Michele Simionato

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top