Does Python need an 'xor' operator?

Bengt Richter bokr at oz.net
Mon Apr 15 16:39:37 EDT 2002


On Mon, 15 Apr 2002 09:34:26 -0400, "Steve Holden" <sholden at holdenweb.com> wrote:

>"Bengt Richter" <bokr at oz.net> wrote ...
>[ ... ]
>> Well, to tie in with existing spelled-out 'and' and 'or' operations,
>> it should probably do something along those lines (i.e., evaluate to
>> one or other of the objects, not one of the boolean values used in the
>logic),
>> but I can't think of something sensible.
>>
>Since in Boolean terms a xor b is equivalent to ((a and not b) or (b and not
>a)), maybe a xor b should return whichever of a or b is not false.
>
>>>> a = 42
>>>> b = 0
>>>> a ^ b
>42
>>>> b ^ a
>42
>>>>
>
>Since that's exactly what it appears to do, stop fiddling with what already
>works !
 >>> a = 42
 >>> b = None
 >>> a ^ b
 Traceback (most recent call last):
   File "<stdin>", line 1, in ?
 TypeError: unsupported operand type(s) for ^: 'int' and 'NoneType'
??

I'm not sure who you're talking to, but my problem was thinking of xor in terms
of short cut evaluation analogous to 'and' and 'or'. Nothing seemed intuitive,
since there is no way to short cut (i.e., have a case sensibly avoiding evaluation
of both terms) an xor.

Regards,
Bengt Richter



More information about the Python-list mailing list