Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do chained assignments work?

A quote from something:

>>> x = y = somefunction() 

is the same as

>>> y = somefunction() >>> x = y 

Question: Is

x = y = somefunction() 

the same as

x = somefunction() y = somefunction() 

?

Based on my understanding, they should be same because somefunction can only return exactly one value.

like image 575
q0987 Avatar asked Sep 29 '11 18:09

q0987


1 Answers

Neither.

x = y = some_function() 

is equivalent to

temp = some_function() x = temp y = temp 

Note the order. The leftmost target is assigned first. (A similar expression in C may assign in the opposite order.) From the docs on Python assignment:

...assigns the single resulting object to each of the target lists, from left to right.

Disassembly shows this:

>>> def chained_assignment(): ...     x = y = some_function() ... >>> import dis >>> dis.dis(chained_assignment)   2           0 LOAD_GLOBAL              0 (some_function)               3 CALL_FUNCTION            0               6 DUP_TOP               7 STORE_FAST               0 (x)              10 STORE_FAST               1 (y)              13 LOAD_CONST               0 (None)              16 RETURN_VALUE 

CAUTION: the same object is always assigned to each target. So as @Wilduck and @andronikus point out, you probably never want this:

x = y = []   # Wrong. 

In the above case x and y refer to the same list. Because lists are mutable, appending to x would seem to affect y.

x = []   # Right. y = [] 

Now you have two names referring to two distinct empty lists.

like image 139
Bob Stein Avatar answered Sep 18 '22 06:09

Bob Stein