Waffling (was Re: single-line terinary operators considered harmful)
Thomas Wouters
thomas at xs4all.net
Thu Mar 6 15:11:02 EST 2003
On Thu, Mar 06, 2003 at 07:28:19PM +0000, Stephen Horne wrote:
> On Thu, 6 Mar 2003 13:03:50 -0700, Steven Taschuk
> <staschuk at telusplanet.net> wrote:
> >Certainly Python's guaranteed evaluation and execution order is
> >very comfortable. There is the occasional oddity:
> > d = {}
> > i = 3
> > i = d[i] = i+1
> >has a surprising (to me) result. But this isn't good style anyway.
> I wondered what you were talking about - until I noticed that...
> >>> d={}
> >>> i=3
> >>> i=d[i]=i+1
> >>> i
> 4 <- this was expected
> >>> d[i]
> 4 <- this was expected
> >>> d
> {4: 4} <- pardon? - why not {3: 4}
> I'm not sure I understand it, but I imagine it has to do with '='
> being n-ary (n >= 2) non-associative (rather than binary
> right-associative). Maybe the assigns are done left-to-right, even
> though the rightmost item is the source and must be evaluated first?
Yes, '=' is a statement, not an expression like in many other languages, and
the chained version is a special case of it, for convenience. The simple
example of
a = b = c = d
would in C be parsed as
a = (b = (c = d))
and executed innermost-first, but in Python, it's more like
(a, b, c) = (d,)*3
(Not quite, but close enough. Use the 'dis' module to see what it really
does :) This does, however, assign from left to right. But you should not
rely on the order! You could call this a wart, but it doesn't make real
sense to change it the other way 'round either, except if you're thinking of
assignment the wrong way 'round anyway. :) And besides, it has a good side
too.. It stops people from writing code like:
i = d[i] = i+1
Evil-wink'ly y'rs,
--
Thomas Wouters <thomas at xs4all.net>
Hi! I'm a .signature virus! copy me into your .signature file to help me spread!
More information about the Python-list
mailing list