Interpreting Left to right?

Ethan Furman ethan at stoneleaf.us
Fri Jun 24 16:13:08 EDT 2011


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


~Ethan~



More information about the Python-list mailing list