Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange Syntax Parsing Error in Python?

Am I missing something here? Why shouldn't the code under the "Broken" section work? I'm 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,
     )
like image 354
user213060 Avatar asked Apr 25 '10 14:04

user213060


People also ask

How do you fix parsing errors in Python?

How do I fix parsing errors? Easily: read a traceback message, rewrite your code accordingly, and re-run the program again. That's one of the reasons why Python is so awesome! It tells you what's wrong with your code in traceback messages so all you have to do is learn to read those messages.

What is a parsing error in Python?

Syntax errors often called as parsing errors, are predominantly caused when the parser detects a syntactic issue in your code.

What Is syntax and SyntaxError in Python?

Syntax errors are mistakes in the use of the Python language, and are analogous to spelling or grammar mistakes in a language like English: for example, the sentence Would you some tea? does not make sense – it is missing a verb. Common Python syntax errors include: leaving out a keyword.


1 Answers

This is the relevant bit from the grammar:

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

The first line here allows putting a comma after the last parameter when not using varargs/kwargs (this is why your first example works). However, you are not allowed to place 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 the grammar:

These are both legal:

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

but this is not:

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

It makes sense not to allow a comma after **kwargs, since it must always be the last parameter. I don't know why the language designers chose not to allow my last example though - maybe an oversight?

like image 152
interjay Avatar answered Sep 23 '22 21:09

interjay