[Python-ideas] XOR

Rob Cliffe rob.cliffe at btinternet.com
Wed Oct 28 01:42:08 CET 2009

I'm not in favour of of adding an xor operator, but it seems to me it IS 
possible to make it behave somewhat analagously to 'and' and 'or' as far as 
what it returns:

    X xor Y   evaluates to:

X if bool(X)==True and bool(Y)==False
Y if bool(Y)==True and bool(X)==False
False if bool(X)==Bool(Y)==True
Y if bool(X)==bool(Y)==False

The last case is analagous to X or Y evaluating to Y when 
bool(X)==bool(Y)==False, e.g.
    0 or []    ==    []
    [] or 0    ==    0

Admittedly there is an aestheically unpleasing asymmetry here.
But it means you could write code such as
    Z = X xor Y
    if Z:
         <do something with Z>
        # Z is known to be either X or Y

Of course, there is no evaluation short-circuiting.
Rob Cliffe

----- Original Message ----- 
From: "Robert Kern" <robert.kern at gmail.com>
To: <python-ideas at python.org>
Sent: Tuesday, October 27, 2009 11:18 PM
Subject: Re: [Python-ideas] XOR

> On 2009-10-27 18:07 PM, geremy condra wrote:
>> On Tue, Oct 27, 2009 at 6:46 PM, Georg Brandl<g.brandl at gmx.net>  wrote:
>>> Sturla Molden schrieb:
>>>> Why does Python have a bitwise but not a logical xor operator?
>>> How often do you need the xor operator?
>> 1) Technically, an operator is *never* needed, as its just syntactic 
>> sugar.
>> 2) It sure would make crypto code look prettier, as we rely on xor
>>      operations extensively.
> No, it wouldn't. Crypto uses the bitwise xor which we already have an 
> operator for: ^.
> As I stated in the referenced thread, to me, the most compelling reason 
> there is no "xor" keyword to go with "and" and "or" is that one cannot 
> make an xor that shares the same short-circuiting behavior. Or the 
> behavior of returning one of the operand objects rather than a coerced 
> bool. Without either of those behaviors, there is little benefit to having 
> a keyword operator where a trivial one-liner will suffice.
> -- 
> Robert Kern
> "I have come to believe that the whole world is an enigma, a harmless 
> enigma
>  that is made terrible by our own mad attempt to interpret it as though it 
> had
>  an underlying truth."
>   -- Umberto Eco
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas 

More information about the Python-ideas mailing list