[Python-ideas] The way decorators are parsng

Chris Rebert pyideas at rebertia.com
Wed Oct 19 23:43:41 CEST 2011


> On Wed, Oct 19, 2011 at 2:32 PM, Tarek Ziadé <ziade.tarek at gmail.com> wrote:
> Hello
>
> Today I've tried to write a one-liner for a decorator, The decorator
> is a method in a class.
>
> I wanted to do something like this:
>
> @Class().decorator()
> def function():
>    ...
>
> That threw a syntax error to my surprise.
<snip>
> Is there something obvious I am missing, or is there a weird thing in
> the way decoratirs are parsed ?

PEP 318 -- Decorators for Functions and Methods
(http://www.python.org/dev/peps/pep-0318/ ):
"Current Syntax
[...]
The decorator statement is limited in what it can accept -- arbitrary
expressions will not work. Guido preferred this because of a gut
feeling [17]."
[17]: http://mail.python.org/pipermail/python-dev/2004-August/046711.html

According to Python 2.7's grammar
(http://docs.python.org/reference/grammar.html ):
    decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
    dotted_name: NAME ('.' NAME)*

So, you're limited to an arbitrarily-long sequence of attribute
accesses, followed by an optional call.

Cheers,
Chris
--
http://rebertia.com



More information about the Python-ideas mailing list