short-circuit behavior anomaly?

logosity wecaputo at thoughtworks.com
Sat Mar 9 02:01:08 EST 2002


Hi,

I was working through this tutorial:
http://gnosis.cx/publish/programming/charming_python_13.txt

Which shows the statements in the following functions (imp and fn) as 
equivalent:

def pr(s): print s

def imp():
    if x == 1: pr('one')
    elif x == 2: pr('two')
    else: pr('other')	
	
def fn():
    (x == 1 and pr('one')) \
 or (x == 2 and pr('two')) \
 or (pr('other'))

Here is a sample program:
x = 1
imp()
x = 2
imp()
x = 3
imp()
print
x = 1
fn()
x = 2
fn()
x = 3
fn()

When run, this produces the following output:
one
two
other

one
other
two
other
other

IOW, the third clause gets evaluated regardless of the outcome of the 
first two clauses.

However, substituting the following in fn() will produce the same 
result as imp():
print (x == 1 and ("one")) or (x == 2 and ('two'))  or ('other')

Implying something to do with the function calls -- if I replace the 
pr('one') call in the line again will cause 'other' to be printed 
after 'one')

I am wondering, is this a mistake in the tutorial, a change in 
behavior between versions (I am using 2.1 and the tutorial seems to 
be written against 2.0), a bug in Python, or something else?

I have looked through the FAQ, browsed the bug list at SF, read the 
relevant sections of the language reference and searched (as best I 
could) the mailing list archive here (and at google), but I can't 
find out what the deal is.

Anyone have any thoughts?

Thanks,
Bill





More information about the Python-list mailing list