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:


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
(1, 2, 3)

a = b = c = 2
b = 3
print a,b,c
>>> 2 3 2

Need Your Help

float bits and strict aliasing

c++ floating-point bits strict-aliasing type-punning

I am trying to extract the bits from a float without invoking undefined behavior. Here is my first attempt:

Where do you store images for mvc projects and how do you reference them from site.master image

I have a new mvc project and i am trying to figure out the best place to store images and also how i would reference them from site.master (in cases where i have a header images that i want...