missing 'xor' Boolean operator
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Fri Jul 17 09:42:44 EDT 2009
On Thu, 16 Jul 2009 15:53:45 +0200, Jean-Michel Pichavant wrote:
> Python has extended the algebra definition of "or" and "and" top any
> type, but it is so unintuitive (I'm no LISP programmer).
I disagree. The Something/Nothing dichotomy is so intuitive to me that I
would hate to go back to a language that only accepted booleans as
arguments to `if`.
> I think than
> using the short-circuiting mechanism of bool operators along with the
> python tricks is just error prone and may result in bug difficult to
> spot, unless you are very aware of all python boolean mechanisms.
In other words, if you don't know how Python behaves, you will make
mistakes.
Of course you will. That applies to *anything* -- if you don't know how
it works, you will make mistakes.
Given three result codes, where 0 means "no error" and an arbitrary non-
zero integer means some error, it is simple and easy to write:
failed = result_1 or result_2 or result_3
The equivalent:
failed = (result_1 != 0) or (result_2 != 0) or (result_3 != 0)
# or if you prefer:
succeeded = (result_1 == 0) and (result_2 == 0) and (result_3 == 0)
are longer and more difficult to read and easier to get wrong. Even worse
are tricks like this:
failed = (result_1 + result_2 + result_3) != 0
This obscures the fact that the result codes are flags and makes it seem
like (flag + flag) is meaningful.
--
Steven
More information about the Python-list
mailing list