short-circuit behavior anomaly? (fwd)

David Mertz, Ph.D. mertz at gnosis.cx
Sat Mar 9 12:57:15 EST 2002


|> http://gnosis.cx/publish/programming/charming_python_13.txt
|> def pr(s): print s
|> def fn():
|>     (x == 1 and pr('one')) \
|>  or (x == 2 and pr('two')) \
|>  or (pr('other'))
|By default, functions return None, which is false.  For this function
|to work right in context below, you must return a true value

That is my tutorial.  I was just about to write apologizing for the
error.  But looking at the file, I don't see the problem there
currently.  I'm not sure whether the problem was with a cached version
of the article that has been fixed; or maybe it is from one of my other
articles on FP in Python.

In any case, Reedy is right about the example.  A better function would
be something like:

    def pr(s):
        print s
        return 1

Btw. There *is* an error in one of my articles, concerning
short-circuiting.  I'm not sure if I corrected it on my web site (but
the IBM dW copy will remain wrong either way).  It was something like:

    # Like C ternary 'cond ? this : that'
    (<<cond>> and this) or that

If this is a false value, the expression doesn't do what is desired.  A
solution is:

    ((<<cond>> and [this]) or [that])[0]

One has to be careful with short-circuiting.  Despite my efforts to
point out some functional styles, sometimes plain ole 'if' blocks are
still clearer.

Yours, David...

--
Keeping medicines from the bloodstreams of the sick; food from the bellies of
the hungry; books from the hands of the uneducated; technology from the
underdeveloped; and putting advocates of freedom in prisons.  Intellectual
property is to the 21st century what the slave trade was to the 16th.




More information about the Python-list mailing list