Interpreting Left to right?

Tycho Andersen tycho at tycho.ws
Fri Jun 24 16:06:18 EDT 2011


On Fri, Jun 24, 2011 at 01:13:08PM -0700, Ethan Furman wrote:
> Tycho Andersen wrote:
> >On Fri, Jun 24, 2011 at 12:14:27AM -0700, Ethan Furman wrote:
> >>The example given to me when I had this question:
> >>
> >>--> x = x['huh'] = {}
> >>--> x
> >>{'huh': {...}}
> >>
> >>
> >>As you can see, the creation of the dictionary is evaluated, and
> >>bound to the name 'x'; then the key 'huh' is set to the same
> >>dictionary.
> >
> >Can you please elaborate? I really don't understand how this works at
> >all. I would have expected a NameError from this (obviously my mental
> >model is wrong).
> >
> >This single line is equivalent to:
> >
> >x = {}
> >x['huh'] = x
> >
> >...but I don't understand how python's evaluation semantics get from
> >the one liner to the two liner/result at all.
> >
> >\t
> 
> Think of it this way:
> 
> x = x['huh'] = {}
> 
> obj = {}       # RHS evaluated first (and only once)
> 
> x = obj        # then first LHS
> 
> x['huh'] = obj # then second LHS, etc

Yes, I understand that, but I guess I don't understand *why* things
are done that way. What is the evaluation order principle at work
here? I would have expected:

tmp = {}
x['huh'] = tmp # NameEror!

That is, the right hand sides of assignments are evaluated before the
left hand sides. That is (somehow?) not the case here.

\t



More information about the Python-list mailing list