short-circuit behavior anomaly?
Christophe Delord
christophe.delord at free.fr
Sat Mar 9 02:31:00 EST 2002
Hi,
There is a bug in 'fn'.
pr always returns None. When x==1, pr('one') is executed (and prints
'one') and returns None so the condition (x==1 and pr('one')) is false.
Finally the last condition will also be evaluated (ps('other')).
you can define pr like this :
def pr(s):
print s
return 1
or define the last condition like this :
or (x not in (1,2) and pr('other'))
Christophe.
logosity wrote:
> 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
>
>
>
--
Christophe Delord
http://christophe.delord.free.fr/
More information about the Python-list
mailing list