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:
tuple
objectMy 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:
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.
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.
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