[Python-ideas] Unpacking iterables for augmented assignment

Tim Peters tim.peters at gmail.com
Sun Aug 26 13:52:05 EDT 2018


[James Lu]
> > Currently, is <expr1> = <expr2> = <expr3> = <expr4> always equivalent
> > to <expr1> = <expr4>; <expr2> = <expr4>; <expr3> = <expr4>?

[Stephen J. Turnbull[
> No.  It's equivalent to
>
>     <expr3> = <expr4>
>     <expr2> = <expr3>
>     <expr1> = <expr2>
>
> and the order matters because the <expr>s may have side effects.

This is tricky stuff.  In fact the rightmost expression is evaluated once,
and then the bindings are done left-to-right using the result of evaluating
the rightmost expression.  Like so:

>>> def return2():
...     print("called return2")
...     return 2
>>> xs = [10, 20, 30, 40]
>>> i = xs[i] = return2()
called return2
>>> xs
[10, 20, 2, 40]
>>> i
2

So James's account is closer to what's done, but is missing weasel words to
make clear that <expr4> is evaluated only once.

Sane code doesn't rely on "left to right", but may well rely on "evaluated
only once".
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180826/2e5299ec/attachment.html>


More information about the Python-ideas mailing list