Does Python need an 'xor' operator?

Steve Holden sholden at holdenweb.com
Mon Apr 15 13:03:50 EDT 2002


"Ken Peek" <Ken.Peek at SpiritSongDesigns.comNOSPAM> wrote in message
news:3cbaebd1 at news.mhogaming.com...
> "Steve Holden" <sholden at holdenweb.com> wrote in message
> news:LHAu8.11094$Ji7.10494 at atlpnn01.usenetserver.com...
>
> | "Bengt Richter" <bokr at oz.net> wrote ...
> |
> | 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 !
>
> NO it DOESN'T!! ::
>
I know, but I suppose I'll have to come clean: I chose the data to support
my argument. As your example shows clearly, the ^ operator is bitwise rather
than what the documentation currently calls a Boolean operator (not, and).

> >>> a = "123"
> >>> b = 0
> >>> a ^ b
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> TypeError: unsupported operand type(s) for ^: 'str' and 'int'
> >>>
>
> 'xor' should return the string '123' in this case-- not an error.  In
other
> words, '^' deals with BITS (as it now does), and 'xor' deals with objects.
>
> I need (in my work) the ability to diddle bits-- these operators need to
"do the
> good thing" when operating on ints (and longs).  I don't want these
operators
> overloaded to recognize other objects-- that is the purpose of 'not',
'or',
> 'and', (and would be operator 'xor').
>
> The operator '!=' performs a similar operation, but always returns a
boolean.
> 'xor' should return the non-false object if the other operand is false,
and
> false if both operands are either true or both operands are false.
>
> The 3 different behaviors of '^', '!=', and 'xor' each have their place in
> writing code...
>
Perhaps so, but since the addition of xor might break code by creating a new
keyword I suspect you would have a difficult time persuading anyone who
counts to do it. So you're stuck with

    (a and not b) or (b and not a)

for the present. Maybe in Python 3?

regards
 Steve







More information about the Python-list mailing list