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

py.log using decorators for DRY

P: n/a
I'm using py.log for logging and I find that I end up having the
following pattern emerge within my code (influenced by
http://agiletesting.blogspot.com/200...library.html):
def foo(**kwargs):
log.foo(kwargs)
#body form

This led me to believe that I could simplify that pattern with the
following idiom :
def logit (fn):
'''
decorator to enable logging of all tagged methods
'''
def decorator (**kwargs):
# call a method named fn.func_name on log with kwargs
#should be something like: log.func_name (kwargs)

return decorator
I can then do add @logit to all my existing methods via a script
(there's a truck load of methods to tag):
@logit
def oldfoo () : pass
My question is in regards to the body form in the decorator. How do I
call that method on the log object at runtime?

(ps. I hope my question is clear $)

Oct 29 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
yoda <no*****@gmail.com> wrote:
I'm using py.log for logging and I find that I end up having the following
pattern emerge within my code (influenced by
http://agiletesting.blogspot.com/200...ng-with-py-lib
rary.html):

def foo(**kwargs):
log.foo(kwargs)
#body form

This led me to believe that I could simplify that pattern with the
following idiom :
def logit (fn):
'''
decorator to enable logging of all tagged methods
'''
def decorator (**kwargs):
# call a method named fn.func_name on log with kwargs
#should be something like: log.func_name (kwargs)

return decorator


Assuming the attributes of object 'log' don't change at runtime (i.e.,
you're OK with early binding), I'd code:

def logit(fn):
method = getattr(log, fn.func_name)
def callit(**kwargs): return method(kwargs)
return callit

If you need to do late binding instead, you can move the getattr to
inside the body of callit.
Alex

Oct 29 '05 #2

P: n/a
I feel so stupid... lol... now why didn't I think of that?

Thanks Alex.

Oct 29 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.