473,238 Members | 3,499 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,238 software developers and data experts.

adding class functionality, nested scoping

Hi,

regarding automatically adding functionality to a class (basically taken
from the cookbook recipee) and Python's lexical nested scoping I have a question wrt this code:

#-----------------
import types

# minor variation on cookbook recipee
def enhance_method(cls, methodname, replacement):
'replace a method with an enhancement'
method = getattr(cls, methodname)
def _f(*args, **kwargs):
return replacement(method, *args, **kwargs)
_f.__name__ = methodname
setattr(cls, methodname, types.MethodType(_f, None, cls))

# loop over class dict and call enhance_method() function
# for all methods to modify
def enhance_all_methods(cls, replacement):
for methodname in cls.__dict__:
if not methodname.startswith("__"):
method = getattr(cls, methodname)
def _f(*args, **kwargs):
return replacement(method, *args, **kwargs)
_f.__name__ = methodname
enhance_method(cls, methodname, replacement)
# Does not work: all enhanced methods only call the last wrapped originial
# method. It seems the name 'method' in the surrounding scope of the
# def _(...) function definition only refers to the last loop value(?)
def ERRONEOUS_enhance_all_methods(cls, replacement):
for methodname in cls.__dict__:
if not methodname.startswith("__"):
method = getattr(cls, methodname)
def _f(*args, **kwargs):
return replacement(method, *args, **kwargs)
_f.__name__ = methodname
setattr(cls, methodname, types.MethodType(_f, None, cls))
class Foo(object):
def foo(self, x):
print "foo", x

def bar(self, x):
print "bar", x
def logme(method, *args, **kwargs):
print "-->", method.__name__, args, kwargs
try:
return method(*args, **kwargs)
finally:
print "<--"
#enhance_all_methods(Foo, logme)
ERRONEOUS_enhance_all_methods(Foo, logme)

foo = Foo()
foo.foo(2)
foo.bar(2)
#-----------------

....give this output:
>>foo = Foo()
foo.foo(2)
--foo (<__main__.Foo object at 0x1b08f0>, 2) {}
foo 2
<--
>>foo.bar(2)
--foo (<__main__.Foo object at 0x1b08f0>, 2) {}
foo 2
<--
>>>
So, while using enhance_all_methods() to add functionality does work, ERRONEOUS_enhance_all_methods() does not. Why is this? Is the explanation I tried to give in the code comment on the right track:

# Does not work: all enhanced methods only call the last wrapped originial
# method. It seems the name 'method' in the surrounding scope of the
# def _(...) function definition only refers to the last loop value(?)

Thanks for any hint,
Holger
--
Psssst! Schon vom neuen GMX MultiMessenger gehört?
Der kann`s mit allen: http://www.gmx.net/de/go/multimessenger?did=10
Jan 4 '08 #1
1 1534
On Jan 4, 10:43*am, jh...@gmx.de wrote:
Hi,
Hi

[...]
# Does not work: all enhanced methods only call the last wrapped originial
# method. It seems the name 'method' in the surrounding scope of the
# def _(...) function definition only refers to the last loop value(?)
def ERRONEOUS_enhance_all_methods(cls, replacement):
* * for methodname in cls.__dict__:
* * * * if not methodname.startswith("__"):
* * * * * * method = getattr(cls, methodname)
* * * * * * def _f(*args, **kwargs):
* * * * * * * * return replacement(method, *args, **kwargs)
* * * * * * _f.__name__ = methodname
* * * * * * setattr(cls, methodname, types.MethodType(_f, None, cls))
This is normal: After ERRONEOUS_enhance_all_methods is called, the
value method is the one from the last iteration of the loop. All
subsequent references to 'method' (in function _f) will return that
last value. To solve this problem you need to fix the object 'method'
is bound to in function _f:

def enhance_all_methods(cls, replacement):
# The following binds 'method' to its current value in _f
def replace(method):
def _f(*args, **kwargs):
return replacement(method, *args, **kwargs)
return _f
for methodname in cls.__dict__:
if not methodname.startswith("__"):
_f = replace(getattr(cls, methodname))
_f.__name__ = methodname
setattr(cls, methodname, types.MethodType(_f, None, cls))

Of course this looks more like your first version, which trims down to
the following and is probably a better option:

def enhance_all_methods(cls, replacement):
for methodname in cls.__dict__:
if not methodname.startswith("__"):
enhance_method(cls, methodname, replacement)

HTH

--
Arnaud

Jan 4 '08 #2

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

Similar topics

6
by: Andy Baker | last post by:
Hi there, I'm learning Python at the moment and trying to grok the thinking behind it's scoping and nesting rules. I was googling for nested functions and found this Guido quote:...
9
by: OKB (not okblacke) | last post by:
For a variety of reasons, I'm interested in putting together some code that will allow me to created structures out of nested classes, something like: class class1: def methA(self): print...
2
by: Victor Liu | last post by:
hi, why n1 in local::f() is no allowed ? int n0; void function() { int n1; static int n2; class local {
7
by: newbiecpp | last post by:
Why this code cannot be compiled (under VC++ 7.0): class Outer { public: class Inner { public: Inner() : in_data(0) {} void action() { Outer::out_data++; // illegal reference to...
12
by: Mortos | last post by:
I need some quick advice. I just need to reference a containing class from the nested class. I'm familiar with Java but C# is proving tricky. public BigClass { public int ID_BigClass = -99; ...
3
by: Carmella | last post by:
Is it possible for a class to create an instance of a private nested class which raises events and then listen for those events? In the example below, when InnerClass sings, OuterClass should say...
19
by: Jamey Shuemaker | last post by:
I'm in the process of expanding my knowledge and use of Class Modules. I've perused MSDN and this and other sites, and I'm pretty comfortable with my understanding of Class Modules with the...
7
by: WXS | last post by:
Vote for this idea if you like it here: http://lab.msdn.microsoft.com/productfeedback/viewfeedback.aspx?feedbackid=5fee280d-085e-4fe2-af35-254fbbe96ee9...
17
by: Jef Driesen | last post by:
Suppose I have a datastructure (actually it's a graph) with one template parameter (the property P for each edge and vertex): struct graph<P>; struct vertex<P>; struct edge<P>; I also have...
3
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 3 Jan 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). For other local times, please check World Time Buddy In...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...

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.