Assignment statement value
Everybody knows that in Python assignments do not return开发者_开发知识库 a value, presumably to avoid assignments on if
statements when usually just a comparison is intended:
>>> if a = b:
File "<stdin>", line 1
if a = b:
^
SyntaxError: invalid syntax
>>> if a == b:
... pass
...
For the same reason, one could suspect that multiple assignments on the same statement were also syntax errors.
In fact, a = (b = 2)
is not a valid expression:
>>> a = (b = 2)
File "<stdin>", line 1
a = (b = 2)
^
SyntaxError: invalid syntax
So, my question is: why a = b = 2
works in Python as it works in other languages where assignment statements have a value, like C?
>>> a = b = c = 2
>>> a, b, c
(2, 2, 2)
Is this behavior documented? I could not found anything about this in the assignment statement documentation: http://docs.python.org/reference/simple_stmts.html#assignment-statements
It's right there in the syntax:
assignment_stmt ::= (target_list "=")+ (expression_list | yield_expression)
The tiny +
at the end of (target_list "=")+
means "one or more". So the line a = b = c = 2
does not consist of 3 assignment statements, but of a single assignment statement with 3 target lists.
Each target list in turn consist only of a single target (an identifier in this case).
It's also in the text (emphasis mine):
An assignment statement [...] assigns the single resulting object to each of the target lists, from left to right.
This can lead to interesting results:
>>> (a,b) = c = (1,2)
>>> (a, b, c)
(1, 2, (1, 2))
Another fine example:
>>a,b,c = b = 1,2,3
>>b
(1, 2, 3)
a = b = c = 2
b = 3
print a,b,c
>>> 2 3 2
精彩评论