Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comma Syntax: rationale behind a hanging comma in a statement being a SyntaxError

Tags:

python

syntax

In Python, a variable or literal followed by a hanging comma is a one-tuple:

1, # (1,)

...and a series of comma-separated variables/literals (whether or not they are followed by a hanging comma) is also a tuple:

1,2, # (1,2)
1,2 # (1,2)

However, inside a callable/function, this syntax is treated differently, because the comma is used for separation of arguments:

bool(5>6,) # False - 5>6 == False
bool((5>6,)) # True - (5>6,) is a non-empty tuple (always True - contents ignored)

The first line seems to simply ignore the hanging comma. The second line creates a one-tuple (as expected). This holds true for user-defined functions as well (don't know why it wouldn't):

def f(arg):
    pass
f(1,) # No Error 

Consider also the following behavior of assert (which is a statement, not a function):

assert 5>6 # AssertionError, as expected 
assert(5>6) # AssertionError, as expected 
assert 5>6, # SyntaxError: invalid syntax
assert(5>6,) # SyntaxWarning: assertion always true, perhaps remove parentheses?
assert 5>6, 'NOPE!' # AssertionError: NOPE!, as expected 

Therefore my interpretation of the treatment of hanging commas is as follows:

  • If the comma is in the context of function arguments, it is ignored
  • If the comma is in the context of a statement, it is a syntax error
  • Elsewhere, it is interpreted as part of a tuple object

My question: is my interpretation of the above behavior correct? Does the Python interpreter simply ignore hanging commas found in argument lists? Does this behavior vary by Python implementation? Finally: WHY is there an inconsistency in the treatment of a hanging comma at the end of a statement (syntax error) and at the end of an argument list (no syntax error)?

EDIT: After reading the answers and thinking it through a bit more, my interpretation should be amended as follows:

  • The hanging comma is ALWAYS IGNORED, except in the following two contexts
  • If the hanging comma is in the context of a statement, it is a syntax error
  • If the hanging comma signals a one-tuple

However, this still leaves the question of WHY the hanging comma is not ignored for supplying arguments to statements, when they are ignored for supplying arguments to functions.

like image 500
Rick supports Monica Avatar asked Feb 10 '23 03:02

Rick supports Monica


1 Answers

The trailing comma is consistently ignored, in any comma-seperated listing (function calls, list/dictionary literals, etc). Your assert example is not a comma-seperated listing.

The only reason the trailing comma is needed for the one-tuple is because there would be no way to differentiate between a one-tuple and a parenthesized expression.

like image 94
orlp Avatar answered Feb 13 '23 13:02

orlp