Does Python need an 'xor' operator?

jepler at unpythonic.net jepler at unpythonic.net
Sun Apr 14 11:17:57 EDT 2002


On Sun, Apr 14, 2002 at 07:56:06AM -0400, John Roth wrote:
> So it's not possible to return one of the operands, we have
> to return True or False. However, now the operation
> is not consistent with 'and' and 'or,' which imposes an
> issue with teaching the language.

You could come up with something more perverse if you want to better keep
the spirit of the 'and' and 'or' operators for 'a xor b'.

If exactly one operand is true, return that operand.  Otherwise, if both
operands are false return 'b'.  If both operands are true, return 'not b'.

This follows (kinda) from the identity
    a xor b == (a or b) and not (a and b)

I'm sure this is in keeping with the spirit of Python.  It doesn't
short circuit, but it returns one of its arguments when possible,
and returns the 'not' of one of its arguments in the fourth case.
There's no short-circuit evaluation, but that's just too bad.

Jeff





More information about the Python-list mailing list