[Python-ideas] Syntax for defining parametric decorators
Mathias Panzenböck
grosser.meister.morti at gmx.net
Mon Jul 9 01:13:40 CEST 2012
On 07/08/2012 10:22 PM, Mike Graham wrote:
> A common stumbling block for new users is writing decorators that take
> arguments. To create a decorator like
>
> @timesn(n)
> def f(y):
> ...
>
> We write code like
>
> def timesn(n)
> def decorator(f):
> def inner(y):
> return n * f(y)
> return inner
> return decorator
>
> which confuses many users and can be a handful to type. I wonder if it
> would be clearer for people to write
>
> def timesn(n)(f):
> def inner(y):
> return n * f(y)
> return inner
>
Why not write this?:
def timesn(n)(f)(y):
return n * f(y)
This would be a currified function. One could implement something like that like this:
def curry(f):
for i in range(f.func_code.co_argcount-1):
f = (lambda f: lambda *args: partial(f,*args))(f)
return f
@curry
def timesn(n,f,y):
return n * f(y)
> which is more concise and looks a lot more like a non-parametric
> decorator someone might have written already. The syntax is mostly
> self-explaining and could potentially be useful in other contexts.
>
> There exist tools like the decorator library to try to simplify this
> already, but in my experience they mostly serve to confuse people
> using decorators for the first time more.
>
> One thing I didn't specify was whether `n` was nonlocal or not and the
> behavior of something that keeps and reuses timesn(some_specific_n)
> multiple times.
>
> Does anyone think a feature like this may be useful?
>
> Regards,
> Mike
More information about the Python-ideas
mailing list