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

Arnaud Delobelle arno at marooned.org.uk
Wed Jan 23 19:42:42 CET 2008


On 23 Jan 2008, at 09:44, Aaron Brady wrote:

>> -----Original Message-----
>> 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:
>> [...]
>
> Following up post from 10/8/07.
>
>> 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
>
> This is equivalent to:
> (1)
>     decorator_withargs= partial( partial, prepartial )

[where partial is as in functools and
prepartial(f, x, y)(z, t) <=> f(z, t, x, y)]

Indeed, and if one restricts decorator_withargs to keyword arguments,  
one can simply define it as:

decorator_withargs = partial(partial, partial)

Which is the curry operator!  So decorator_withargs is some sort of  
curry. In fact I had never realised before that this was a way to  
define curry (for functions with 2 arguments)

curry = partial(partial, partial)

[if f is a two-arguments function then curry(f)(x)(y) is f(x, y)]

This means that a meta-decorator (i.e. a decorator for decorators) is  
a kind of currying operator.

> Intriguing.

!

-- 
Arnaud





More information about the Python-ideas mailing list