From the section 7.2 of the language reference, Assignment statements
An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right.
The first assignment statement
a = b, c = d = 1, 2
^ ^ ^ ^
| | | +-- expression list
| | +-- target #3
| +-- target #2
+-- target #1
consists of the expression list 1, 2
(which evaluates to a tuple) and three targets a
, b, c
, and d
, which are assigned in the following order:
a = 1, 2
b, c = 1, 2
d = 1, 2
There is no casting involved. The assignments to a
and d
assign the tuple directly; the assignment to b
and c
pairs each target with a corresponding value in the tuple.
Perhaps most notably, it is not like in C where an assignment is considered an expression whose value is the value that was assigned. Something like a = b = c = d
in C is equivalent to
/* C with explicit parentheses
* d is assigned to c, with the value of c = d assigned
* to b, and the value of b = c = d assigned to a
*/
a = (b = (c = d))
while in Python it is a single statement with the semantics defined above.
A common idiom in C is to use the value of an assignment in a conditional statement, so that you can bind the value being tested to a variable used later in the same statement.
while ((c = foo()) != bar) {
printf("%s\n", c)
}
Prior to the introduction of the assignment expression in Python, the equivalent required a separate assignment statement before and in the while
statement:
c = foo()
while c != bar:
print(c)
c = foo()
or more idiomatically, an infinite loop with an explicit break condition
while True:
c = foo()
if c == bar:
break
print(c)
With the assignment expression, you can now embed an assignment into a boolean-valued expression similar to the C example.
while (c := foo()) != bar:
print(c)