[Python-Dev] chained assignment weirdity

Steven D'Aprano steve at pearwood.info
Wed Nov 7 23:29:27 CET 2012


On 08/11/12 08:39, Ned Batchelder wrote:

> Just to be clear: the reference guide says that the behavior *SHOULD BE* (but is not yet) this:
>
> Python 3.3.0
>> >> {print("a"):print("b")}
> a
> b
> {None: None}


That was the behaviour of Python 2.4:

py> def pr(x):
...     print x
...
py> {pr(1): pr(2), pr(3): pr(4)}
1
2
3
4
{None: None}


2.5 changed to the behaviour seen now, that is, it prints 2 1 4 3
in that order.


>> >> d = {}
>> >> d[print("a")] = print("b")
> b
> a
>
> Is this or is this not "weird" to you?

Not weird to me. The first case has no assignment, so it operates
left to right without exception. The second case has an assignment,
so it operates left to right with a single exception, the right
hand side of the assignment is evaluated before the left hand side(s).

This gives a single, intuitive[1] order of evaluation (left to right),
with the fewest number of exceptions necessary[2]. Using Python 2.4
again:


py> d = {}
py> d[pr(1)] = d[pr(2)] = d[pr(3)] = pr(4) is pr(5)
4
5
1
2
3





[1] Well, intuitive to those whose native language reads left to right.

[2] I assume it is necessary.



-- 
Steven


More information about the Python-Dev mailing list