@decorator syntax is sugar, but for what exactly? (decorator libraries).

Roy Smith roy at panix.com
Sun Aug 8 10:46:38 EDT 2004


In article <mailman.1360.1091975279.5135.python-list at python.org>,
 Andrew Durdin <adurdin at gmail.com> wrote:

> On Sun, 08 Aug 2004 10:19:19 -0400, Roy Smith <roy at panix.com> wrote:
> > 
> > The key question is whether the decorator mechanism would allow such a
> > thing?  All of the examples I've seen have the decorator defined right
> > before it's used, and having a simple name.  I'm guessing that the real
> > syntax is @<callable>, and that any expression that evaluations to a
> > callable object is kosher after the "@"?
> 
> There was some discussion about this on python-dev, and the BDFL's
> conclusion was that arbitrary expressions were not allowed, but only
> dotted names (with optional parentheses), i.e.:
> 
> @decorator
> @module_or_object.decorator
> @func_returning_decorator(args)
> @module_or_object.func_returning_decorator(args)
> 
> (With presumably multiple dotted levels allowed, e.g. module.object.decorator)
> 
> See http://www.python.org/dev/doc/devel/ref/function.html for the
> grammar definition.

Wow, I'm glad I asked.  That answer is quite surprising, and somewhat 
disconcerting.  Lot's of special cases going on here, which is bad.

BTW, I don't understand one of the examples in the grammar.  It says:

>  If there are multiple decorators, they are applied in reverse order. For 
>  example, the following code:
> 
> @f1
> @f2
> def func(): pass
> 
>  is equivalent to:
> 
> def func(): pass
> func = f2(f1(func))

I don't see what that's described as "reverse order".  To my eye, 
they're applied in the order they're specified.  First you apply f1, 
then you apply f2.  The code above is the same as:

func = f1 (func)
func = f2 (func)

Reverse order to me would imply:

func = f1(f2(func))

-or-

func = f2 (func)
func = f1 (func)

i.e. you apply the last one first, as if you had pushed the decorators 
onto a stack and processed them by popping the stack.

I'm not arguing that the semantics should be changed, but that using the 
phrase "reverse order" to describe the semantics is confusing.



More information about the Python-list mailing list