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,
)
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.
Syntax errors often called as parsing errors, are predominantly caused when the parser detects a syntactic issue in your code.
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With