[Python-ideas] An easier syntax for writing decorators (& similar things)?

Arnaud Delobelle arno at marooned.org.uk
Mon Oct 8 19:42:33 CEST 2007

On 8 Oct 2007, at 10:57, Arnaud Delobelle wrote:

> On Mon, October 8, 2007 4:33 am, Adam Atlas wrote:
>> When writing decorators especially when it's one that needs arguments
>> other than the function to be wrapped, it often gets rather ugly...
> Whhy not create a (meta-)decorator to do this? Something like:

To follow up on my untested suggestion, here's one that is tested:

# This metadecorator hasn't changed

def decorator_withargs(decf):
     def decorator(*args, **kwargs):
         def decorated(f):
             return decf(f, *args, **kwargs)
         return decorated
     return decorator

# Here's how to use it to create a decorator

def mydec(f, before='entering %s', after='%s returns %%s'):
     before = before % f.__name__
     after = after % f.__name__
     def decorated(*args, **kwargs):
         print before
         result = f(*args, **kwargs)
         print after % result
         return result
     return decorated

# Now I can decorate a function with my new decorator

@mydec(before='-> %s', after='%s -> %%s')
def f(x):
     print x
     return x+1


 >>> f(1)
-> f
f -> 2


More information about the Python-ideas mailing list