[Python-ideas] Syntax for defining parametric decorators
Calvin Spealman
ironfroggy at gmail.com
Mon Jul 9 14:28:58 CEST 2012
On Sun, Jul 8, 2012 at 4:22 PM, Mike Graham <mikegraham at gmail.com> 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
>
> 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?
While I'm a bit taken aback by the syntax, I recognize this is mostly
because I'm
not used to it. Objectively, it makes enough sense that I think it
fits. I think even
if the only use case is decorator factories, they are a useful enough
thing that this
is okay. We have a specific syntax to support using decorators, why
not better support
writing them?
Still, I'd like to see any ideas people have for alternative uses for
this syntax.
> Regards,
> Mike
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas
--
Read my blog! I depend on your acceptance of my opinion! I am interesting!
http://techblog.ironfroggy.com/
Follow me if you're into that sort of thing: http://www.twitter.com/ironfroggy
More information about the Python-ideas
mailing list