why does this happen? (messed up previous post)
Remco Gerlich
scarblac at pino.selwerd.nl
Mon Feb 12 03:43:43 EST 2001
Dan Parisien <dan at eevolved.com> wrote in comp.lang.python:
> key = "key"
> dict = {"key":None}
> key = dict[key] = "newval"
>
> print key
> >>> newval
> print dict
> >>> {"key":None, "newval":"newval"}
>
> I was expecting
> print dict
> >>>{"key":"newval"}
In C, = is an expression. a = b = c therefore means a = (b = c).
In Python, = is a statement, and a = b = c is simply a shorthand for
a = c; b = c. And that obviously happens left to right. This is also the
reason why in Python "a = (b = c)" is illegal.
I'd consider 'key = dict[key] = "newval"' to be deliberately confusing.
Once you're depending on the order of that sort of thing, your code is hard
to read. I had no idea what to expect when I read it, really.
Use the multiple = when you are setting several similar variables to the
same value, length = width = height = 1, but don't try to make the meaning
of one of them depend on the value of another...
--
Remco Gerlich
More information about the Python-list
mailing list