473,548 Members | 2,585 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Improved super/autosuper

http://aspn.activestate.com/ASPN/Coo.../Recipe/286195

This is a new version of super that automatically determines which
method needs to be called based on the existing stack frames. It's much
nicer for writing cooperative classes. It does have more overhead, but
at this stage I'm not so concerned about that - the important thing is
it actually works.

Note that this uses sys._getframe() magic ...

import sys

_builtin_super = super

def super (self, *p, **kw):
"""
Automatically determine the correct super method and call it.

If there is no corresponding super method, there is no effect
(super just
returns None). This assists in creating cooperative base
classes.

This function is designed to be used with the autosuper
metaclass.

Example of usage:

__metaclass__ = autosuper

class A:

def __init__ (self, a, b):
print 'A.__init__'
print a, b
self.super(a, b)

class B (A):

def __init__ (self, a, b):
print 'B.__init__'
self.super(a, b)

B(1, 2)

produces:

B.__init__
A.__init__
1 2
"""

f = sys._getframe() .f_back

# Make sure that we're being called from a bound method
instance = f.f_locals[f.f_code.co_var names[0]]
assert self is instance

# We'll need this to look up the correct method in the base
classes
fname = f.f_code.co_nam e

# Find the method we're currently running by scanning the MRO
and comparing
# the code objects - when we find a match, that's the class
whose method
# we're currently executing.
s = None
si = None

for c in type(self).__mr o__:
try:
m = getattr(c, fname)
except AttributeError:
continue

if m.im_func.func_ code is f.f_code:
s = c
break

# We should *never* fail to find the current class
assert s is not None

# Try to get a base class method. If we don't find one, we're
finished.
try:
m = getattr(_builti n_super(s, self), fname)
except AttributeError:
return None

# If the code object for the super class is the same as the
current code
# object, we've actually picked up the current class again -
which would
# lead to infinite recursion. So we're finished.
try:
if m.func_code is f.f_code:
return None
except AttributeError:
func_code = None

if m is None:
return None

return m(*p, **kw)

class autosuper (type):
def __init__(cls, name, bases, dict):
setattr(cls, 'super', super)

if __name__ == '__main__':

__metaclass__ = autosuper

class A:
def __init__ (self):
print 'A.__init__'
self.super()

def test (self):
print 'A.test'
self.super()

class B (A):
def __init__ (self):
print 'B.__init__'
self.super()

def test (self):
print 'B.test'
self.super()

class C (A):
def __init__ (self):
print 'C.__init__'
self.super()

def test (self):
print 'C.test'
self.super()

class D (B, C):
def __init__ (self):
print 'D.__init__'
self.super()

def test (self):
print 'D.test'
self.super()

A().test()
print
B().test()
print
C().test()
print
D().test()

---------- Run ----------
A.__init__
A.test

B.__init__
A.__init__
B.test
A.test

C.__init__
A.__init__
C.test
A.test

D.__init__
B.__init__
C.__init__
A.__init__
D.test
B.test
C.test
A.test

Output completed (0 sec consumed) - Normal Termination

Tim Delaney

Jul 18 '05 #1
0 1491

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
2312
by: Kerim Borchaev | last post by:
Hello! Always when I use "super" I create a code duplication because class used as first arg to "super" is always the class where the method containing "super" was defined in: ''' class C: def method(self): super(C, self).method() '''
2
1665
by: Clarence Gardner | last post by:
The super object is considered a solution to the "diamond problem". However, it generally requires that the ultimate base class know that it is last in the method resolution order, and hence it should not itself use super (as well as supplying the ultimate implementation of an overridden method.) However, a problem comes up if that ultimate...
11
5013
by: Nicolas Lehuen | last post by:
Hi, I hope this is not a FAQ, but I have trouble understanding the behaviour of the super() built-in function. I've read the excellent book 'Python in a Nutshell' which explains this built-in function on pages 89-90. Based on the example on page 90, I wrote this test code : class A(object): def test(self): print 'A'
0
1229
by: Michele Simionato | last post by:
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):
10
2115
by: Chris Green | last post by:
Good day, I've done a bit of searching in the language reference and a couple pages referring the behavior of super() but I can't find any discussion of why super needs the name of the class as an argument. Feel free to point me into the bowels of google if this has been discussed to death already. super(self).method() seems like super...
6
2001
by: Steven Bethard | last post by:
When would you call super with only one argument? The only examples I can find of doing this are in the test suite for super. Playing around with it: py> class A(object): .... x = 'a' .... py> class B(A): .... x = 'b' ....
7
5233
by: Kent Johnson | last post by:
Are there any best practice guidelines for when to use super(Class, self).__init__() vs Base.__init__(self) to call a base class __init__()? The super() method only works correctly in multiple inheritance when the base classes are written to expect it, so "Always use super()" seems like bad advice. OTOH sometimes you need super() to get...
9
2190
by: Mike Krell | last post by:
I'm reading Alex Martelli's "Nutshell" second edition. In the section called "Cooperative superclass method calling", he presents a diamond inheritance hierachy: class A(object): def met(self): print "A.met" class B(A): def met(self): print "B.met"
4
1714
by: ddtl | last post by:
Hello everybody. Consider the following code: class A(object): def met(self): print 'A.met' class B(A): def met(self):
0
7707
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7951
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7466
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6036
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5362
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5082
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3495
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
1926
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1051
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.