Re: Calling instance methods from a decorator
- From: "Diez B. Roggisch" <deets@xxxxxxxxxxxxx>
- Date: Fri, 30 May 2008 19:40:17 +0200
Kirk Strauser schrieb:
I'm trying to write a decorator that would do something like:
def trace(before, after):
def middle(func):
def inner(*args, **kwargs):
func.im_self.debugfunction(before)
result = func(*args, **kwargs)
func.im_self.debugfunction(after)
return result
return inner
return middle
class Foo(object):
def __init__(self, myname):
self.name = myname
def debugfunction(self, message):
print 'Instance %s says: %s' % (self.name, message)
@trace('calling', 'finished')
def bar(self, arg):
print arg
Instance snake says: callingFoo('snake').bar(123)
123
Instance snake says: finished
The gotcha seems to be that there's no way to get to 'self' from within the
"inner" function, since func will only have the "normal" attributes:
['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get__', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name']print dir(func)
There's no nice im_self to bounce off of or anything. I seem to be going
about this all wrong. What's a good approach to get the desired effect?
Of course you can get the self - just use the first paramter, because it *is* self. Self is just a parameter - nothing special.
Alternatively, declare inner like this:
def inner(self, *args, **kwargs):
...
try:
return func(self, *args, **kwargs)
finally:
....
Note the additional try/finally. It's got nothing todo with your original problem - but you should use it to guarantee that your trace gets called when leaving the call.
Diez
.
- Follow-Ups:
- Re: Calling instance methods from a decorator
- From: Kirk Strauser
- Re: Calling instance methods from a decorator
- References:
- Calling instance methods from a decorator
- From: Kirk Strauser
- Calling instance methods from a decorator
- Prev by Date: Calling instance methods from a decorator
- Next by Date: Re: A video introducing Ulipad, an IDE mainly for Python
- Previous by thread: Calling instance methods from a decorator
- Next by thread: Re: Calling instance methods from a decorator
- Index(es):
Relevant Pages
|