py.log using decorators for DRY

Alex Martelli aleaxit at
Sat Oct 29 19:50:38 CEST 2005

yoda <nochiel at> 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
> rary.html):
> def 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.


More information about the Python-list mailing list