Calling instance methods from a decorator
- From: Kirk Strauser <kirk@xxxxxxxxxx>
- Date: Fri, 30 May 2008 12:19:56 -0500
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?
--
Kirk Strauser
The Day Companies
.
- Follow-Ups:
- Re: Calling instance methods from a decorator
- From: Diez B. Roggisch
- Re: Calling instance methods from a decorator
- Prev by Date: Re: Generating event from event
- Next by Date: Re: Calling instance methods from a decorator
- Previous by thread: Re: help
- Next by thread: Re: Calling instance methods from a decorator
- Index(es):
Relevant Pages
|