473,785 Members | 2,374 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 1513

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

Similar topics

4
2331
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
1678
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 base class is also the base class for another which inherits from it and another independent base...
11
5035
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
1240
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
2136
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 could just do the right thing...
6
2014
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
5260
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 correct behaviour. ISTM "Only use super() when you know you need it" might be
9
2202
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
1722
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
9646
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10157
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10096
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 most users, this new feature is actually very convenient. If you want to control the update process,...
1
7504
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6742
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5386
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4055
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
2
3658
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2887
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.