Python syntax parsing error?

Am I missing something? Why shouldn't the code in the "Broken" section work? I am using Python 2.6.

#!/usr/bin/env python def func(a,b,c): print a,b,c #Working: Example #1: p={'c':3} func(1, b=2, c=3, ) #Working: Example #2: func(1, b=2, **p) #Broken: Example #3: func(1, b=2, **p, ) 
+7
python syntax-error
source share
2 answers

This is the corresponding bit from grammar :

 arglist: (argument ',')* (argument [','] |'*' test (',' argument)* [',' '**' test] |'**' test) 

The first line allows you to put a comma after the last parameter when varargs / kwargs is not used (this is why your first example works). However, you are not allowed to put a comma after the kwargs parameter if it is specified, as shown in the second and third lines.

By the way, here is an interesting thing shown by grammar:

They are legal:

 f(a=1, b=2, c=3,) f(*v, a=1, b=2, c=3) 

but this is not so:

 f(*v, a=1, b=2, c=3,) 

It makes sense not to allow a comma after **kwargs , since it should always be the last parameter. I donโ€™t know why the language designers decided not to allow my last example - perhaps supervision?

+9
source share

Python usually resolves extra commas at the end of commas (in argument lists and container literals). The main purpose of this is to make code creation a bit easier (you don't have a special case for the last element or a double special case for a singleton tuple).

In the grammar definition **kwargs extends separately and without an extra extra comma. This would by no means help with anything practical like code generation (** kwargs will always be the last thing, so you donโ€™t have to do anything in the special case), so I donโ€™t know why Python will support it.

+5
source share

All Articles