Operator precedences

Hans Nowak wurmy at earthlink.net
Wed Feb 26 20:54:08 EST 2003


Steven Taschuk wrote:
> Quoth Hans Nowak:
>   [...]
> 
>>3 < 2 < 1 is equivalent to 3 < 2 and 2 < 1, including the shortcut effect of 
>>the and operator.
> 
> But not including any side-effects of the middle expression:
>     >>> def spam():
>     ...     global i
>     ...     i += 1
>     ...     return i
>     ...
>     >>> i = 0
>     >>> 0 < spam() < 2
>     1
>     >>> i = 0
>     >>> 0 < spam() and spam() < 2
>     0

Also:

 >>> def f(x):
	print x, "!"
	return x

 >>> f(0) < f(1) < f(2)
0 !
1 !
2 !
1
 >>> f(0) < f(1) and f(1) < f(2)
0 !
1 !
1 !
2 !
1

Hm, I guess that means that in f(0) < f(1) < f(2) it computes f(1) only once, 
then keeps the result around for the other comparison.

Another little trap for the unaware... although this is unlikely to cause major 
problems unless your code is all messed up to begin with. :-)

Cheers,

-- 
Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA=='))
# decode for email address ;-)
The Pythonic Quarter:: http://www.awaretek.com/nowak/
Kaa:: http://www.awaretek.com/nowak/kaa.html
Soon: http://zephyrfalcon.org/





More information about the Python-list mailing list