packing unpacking depends on order.

Steven D'Aprano steve at pearwood.info
Thu Sep 3 03:45:53 CEST 2015


On Thu, 3 Sep 2015 04:06 am, Ian Kelly wrote:

> On Wed, Sep 2, 2015 at 11:42 AM, Terry Reedy <tjreedy at udel.edu> wrote:
>> On 9/2/2015 6:01 AM, Antoon Pardon wrote:
>>>
>>>
>>>>>> a = [1, 2, 3, 4, 5]
>>>>>> b = 1
>>>>>> b, a[b] = a[b], b
>>>>>> a
>>>
>>> [1, 2, 1, 4, 5]

[...]

> I do. I think the former behavior is surprising, and that relying on
> it would result in confusing, hard-to-read code. If you really want
> the former, you can easily reproduce it with:

Of course it's confusing, but the alternative is even more confusing.

b, a[b] = 1, 2

currently has simple, predictable semantics: evaluate the right hand side
from left to right, then assign to the left hand side bindings from left to
right. The order of assignments does not depend on where the right hand
side values come from, or whether a or b already exist. This will work
fine:

assert "a" not in locals() and "b" not in locals()
b, a, a[b] = 1, "CORD".split(), "A"


What's the alternative? I asked this question earlier, and got no answer --
apparently at least three people prefer behaviour that they cannot explain
how to get the results they want :-)

As far as I am concerned, having both of these:

    b, a[b] = a[b], b
    a[b], b = b, a[b]

result in the same bindings is not only hard to implement, but hard to
explain and hard to think about. Try to write an algorithm that gives the
result you want, one which supports all the cases including the case where
one or both of a and b don't exist prior to the assignments.



-- 
Steven



More information about the Python-list mailing list