7

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,
     )
4
  • 2
    When I try this code under Python 2.6, I get a syntax error at line 19 (the second Working). Commented Apr 25, 2010 at 15:04
  • Thanks, corrected minor typo in example #2. Commented Apr 25, 2010 at 15:07
  • 1
    And (not unimportant): why would you want this extraenous comma (except for researching this behaviour)? Commented Apr 25, 2010 at 15:09
  • 1
    The trailing comma helps my eyes see that the expression is not over yet. This would help for a very long line, for example. Also, I always put trailing commas in case I want to paste in more parameters without having to modify the previous line (although that is not applicable in this instance.) Commented Apr 25, 2010 at 15:15

2 Answers 2

9

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?

Sign up to request clarification or add additional context in comments.

Comments

5

Python usually allows extra commas at the end of comma-lists (in argument lists and container literals). The main goal for this is to make code generation slightly easier (you don't have to special-case the last item or double-special-case a singleton tuple).

In the definition of the grammar, **kwargs is pulled out separately and without an extra optional comma. It wouldn't ever help with anything practical like code generation (**kwargs will always be the last thing so you do not have to special-case anything) as far as I can imagine, so I don't know why Python would support it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.