[Python-ideas] Syntax for defining parametric decorators

Terry Reedy tjreedy at udel.edu
Thu Jul 12 04:19:01 CEST 2012


On 7/8/2012 4: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
>
> 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.

As others have noted, this is a proposal for introducing optional 
automatic function currying to python. Parametric decorators are an 
obvious use case, because they require double function nesting, but 
neither the interpreter not the function, such as timesn, would know or 
care how the function will be used. If you are really concerned 
specifically about decorator expressions, I think someone suggestion of 
a new decorator function in functools would be the better way to go.

For people 'raised' with imperative languages without nested functions 
and currying, function currying is definately *not* 'self-explaining'. 
The difficultly is conceptual, not syntactical. I am 99% sure it would 
result in more confusion, not less.

> 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?

Just about every proposal would be 'useful' to someone in some 
situations. Is it useful enough to justify the costs?  My brief answer 
is that the syntactic sugar of automatic currying only applies to a few 
situations and does not add any new functionality. It would be another 
thing to learn, which most people would not get until they learned the 
more general explicit nesting. For some people, say from always-curried 
languages, it might be an attractive nuisance in that they would use it 
and incur the added overhead when it is pointless.

-- 
Terry Jan Reedy




More information about the Python-ideas mailing list