Why can't I xor strings?
Andrew Dalke
adalke at mindspring.com
Sun Oct 10 05:42:11 EDT 2004
Grant Edwards wrote:
> What if you saw
>
> string1 xor string2?
>
> Wouldn't you expect it to be equivalent to
>
> (string1 and (not string2)) or ((not string1) and string2)
I would expect it to give a syntax error.
If not, and 'xor' did become a new boolean operator
in Python I would expect it to act more like
xor_f(x, y)
where 'xor_f' the function is defined as
def xor_f(x, y):
x = bool(x)
y = bool(y)
return (x and not y) or (not x and y)
Why the distinction? In your code you call bool on
an object at least once and perhaps twice. The
truth of an object should only be checked once. You
also have asymmetric return values. Consider
s1 s2 s1 xor s2
"A" "B" False
"A" "" True
"" "B" "B"
"" "" False
Esthetics suggest that either "A"/"" return "A" or that
""/"B" return True. Mine does the latter. Yours does
neither. Probably the Pythonic way, assuming 'xor'
can be considered Pythonic, is to return the object
which gave the True value, like this
def xor_f(x, y):
bx = bool(x)
by = bool(y)
if bx:
if not by:
return bx
return False
else:
if by:
return by
return False
In any case, 'xor' the binary operator is rarely
needed and as you've shown can be interpreted in
a couple different ways. Each alone weighs against
it. Both together make it almost certainly a bad
idea for Python.
Andrew
dalke at dalkescientific.com
More information about the Python-list
mailing list