Eric Eric - 6 months ago 11
Python Question

Strange syntax specification for python decorators

The syntax specification for function definitions:

funcdef ::= [decorators] "def" funcname "(" [parameter_list] ")" ["->" expression] ":" suite
decorators ::= decorator+
decorator ::= "@" dotted_name ["(" [parameter_list [","]] ")"] NEWLINE
dotted_name ::= identifier ("." identifier)*
parameter_list ::= (defparameter ",")*
| "*" [parameter] ("," defparameter)* ["," "**" parameter]
| "**" parameter
| defparameter [","] )
parameter ::= identifier [":" expression]
defparameter ::= parameter ["=" expression]
funcname ::= identifier


Seems to suggest the following is syntactically valid:

@some.dotted.name(*what : "is this")
def my_func(x):
pass


Yet it is not accepted by the interpreter. Am I misreading the grammar, or is the grammar incorrect?

Answer

Looks like a documentation bug to me.

It was

decorator      ::=  "@" dotted_name ["(" [argument_list [","]] ")"] NEWLINE

until v3.2, when argument_list changed to parameter_list. That cannot be right, although whoever submitted the one-line patch evidently thought otherwise.

The grammar itself was not modified. It still says:

decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE

And since that is:

the full Python grammar, as it is read by the parser generator and used to parse Python source files

I think we can conclude that Python decorators still have the syntax we all expect.

Comments