Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comma operator precedence

Tags:

python

Couldn't find a unified resource that documents/explains this. I'm puzzled; is it an operator or not? Most importantly, what is its precedence? An example:

import functools
def array_sum(array):
    return functools.reduce(lambda acc, curr: acc + curr, array)
print(array_sum([1,2])) # 3
# https://docs.python.org/3/reference/expressions.html#operator-precedence tells us that lambda has the lowest precedence.
# But the above code works, which means the comma gets applied after the lambda expression.
# If the comma was applied first, that would give us this runtime error: TypeError: reduce expected at least 2 arguments, got 1

Note that the comma isn't even listed as an operator in the link in the code comments. But here it is called an operator: https://docs.python.org/3/reference/expressions.html#parenthesized-forms

Python version: 3.7.4


EDIT:

I had originally provided this as an additional but incorrect example:

x = 4 if False else 3, 2
print(x) # (3,2)
x = 4 if True else 3, 2
print(x) # 4
# comma was applied before assignment operator

x, y = 4 if True else 3, 2
print(x) # 4
print(y) # 2
# comma was applied after assignment operator

But that was my mistake, because

x = 4 if True else 3, 2
print(x) # 4

was incorrect, and after running it again I saw that when corrected it is:

x = 4 if True else 3, 2
print(x) # (4, 2)

Therefore the comma precedence is behaving consistently in the example that was removed in the edit.

like image 794
habit Avatar asked Sep 10 '19 20:09

habit


1 Answers

The documentation of Assignment Statements makes a distinction between assigning to a single target or multiple targets.

If the target list is a single target with no trailing comma, optionally in parentheses, the object is assigned to that target.

So in the first case, the RHS of the assignment (called the "object" in the documentation) is parsed as a single object. The comma is parsed as the value of the else clause of the conditional expression.

Else: The object must be an iterable with the same number of items as there are targets in the target list, and the items are assigned, from left to right, to the corresponding targets.

So in this case it first tries to parse the RHS as an iterable expression with two items. The comma is treated as the delimiter between the items in a generator expression.

like image 181
Barmar Avatar answered Nov 05 '22 16:11

Barmar