missing 'xor' Boolean operator

Chris Rebert clp2 at rebertia.com
Tue Jul 14 16:22:20 EDT 2009

> Mark Dickinson wrote:
>> On Jul 14, 7:25 pm, "Dr. Phillip M. Feldman" <pfeld... at verizon.net>
>> wrote:
>>> Current Boolean operators are 'and', 'or', and 'not'.  It would be nice
>>> to
>>> have an 'xor' operator as well.
>> Hmm.  I don't think 'nice' is sufficient.  You'd need to make the case
>> that it's sufficiently useful to justify adding a new keyword 'xor' to
>> the language;  I suspect that would be an uphill struggle. :)
>> I'll just note that:
>> (1) It's easy to emulate xor:  'x xor y' <-> bool(x) != bool(y)
>> (2) 'and' and 'or' are special in that they have useful short-
>> circuiting behaviour; xor doesn't have this property (that is, you
>> always need to evaluate *both* operands to determine the result).
>> I'd also guess that 'xor' would be much less used than 'and' or 'or',
>> but maybe that's just a reflection of the sort of code that I tend to
>> write.
On Tue, Jul 14, 2009 at 12:56 PM, Dr. Phillip M.
Feldman<pfeldman at verizon.net> wrote:
> Here's a related issue: I would like to see an option for type checking on
> operands of logical operators, so that attempting to apply a logical
> operator to non-Boolean entities generates a warning message.  With operand
> type checking, 'xor' and != would be different.

That's probably not gonna happen. Python is dynamically and duck
typed, and has a sweet coercion system (__bool__ or __nonzero__
depending on your version) to coerce non-booleans to booleans in a
sensible and useful way. So, it's not gonna change any time soon.

Some illustrative examples:
>>> #empty containers considered false
>>> bool([] or {} or set() or "")
>>> False
>>> #zero and null considered false
>>> bool(0 or None)
>>> False
>>> #anything else is, by default, true
>>> bool(object())
>>> True

And like I said, a class can override a special method to provide
whatever boolean semantics are desired. It's surprisingly handy.


More information about the Python-list mailing list