By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,586 Members | 1,051 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,586 IT Pros & Developers. It's quick & easy.

Wrapping a method twice

P: n/a
Hi all,
given the following code:

---
def append(method,bottom):
def wrapped(*args, **kwargs):
res = method(*args, **kwargs)
return bottom(res,*args, **kwargs)
setattr(method.im_class,method.__name__,wrapped)

def prepend(method,top):
def wrapped(*args, **kwargs):
top(*args, **kwargs)
return method(*args, **kwargs)
setattr(method.im_class,method.__name__,wrapped)
def test():
class C:
def f(self):
print "f"

def pre(self):
print "pre"

def post(res,self):
print "post"

prepend(C.f,pre)
append(C.f,post)
C().f()
---

how comes that test() only outputs:

pre
f

rather than what I expected:

pre
f
post

Thanks very much in advance,
cheers,
Nicolas
Jun 27 '08 #1
Share this Question
Share on Google+
2 Replies

P: n/a
Nicolas Girard napisał(a):
prepend(C.f,pre)
This wraps f, returns wrapped and binds it to C.f (but the
method.__name__ is still wrapped).
append(C.f,post)
This wraps wrapped (the one previously returned), returns wrapped (a
new one) and binds it to C.wrapped (since that is what its
method.__name__ says).
C().f()
If you try C().wrapped() it works as expected.

So the problem is in retaining the function name. Try:

def append(method,bottom):
def wrapped(*args, **kwargs):
res = method(*args, **kwargs)
return bottom(res,*args, **kwargs)
wrapped.__name__ = method.__name__
setattr(method.im_class,method.__name__,wrapped)

def prepend(method,top):
def wrapped(*args, **kwargs):
top(*args, **kwargs)
return method(*args, **kwargs)
wrapped.__name__ = method.__name__
setattr(method.im_class,method.__name__,wrapped)
Jun 27 '08 #2

P: n/a
On Jun 25, 1:52*pm, marek.ro...@wp.pl wrote:
>Try:

def append(method,bottom):
* * def wrapped(*args, **kwargs):
* * * * res = method(*args, **kwargs)
* * * * return bottom(res,*args, **kwargs)
* * wrapped.__name__ = method.__name__
* * setattr(method.im_class,method.__name__,wrapped)

def prepend(method,top):
* * def wrapped(*args, **kwargs):
* * * * top(*args, **kwargs)
* * * * return method(*args, **kwargs)
* * wrapped.__name__ = method.__name__
* * setattr(method.im_class,method.__name__,wrapped)
If you are using Python 2.5, consider functools.update_wrapper, which
also sets __module__,
__doc__ and other attributes.
Jun 27 '08 #3

This discussion thread is closed

Replies have been disabled for this discussion.