Why can't I xor strings?

Jeremy Bowers jerf at jerf.org
Sun Oct 10 15:25:16 EDT 2004


On Sun, 10 Oct 2004 15:30:32 +0000, Grant Edwards wrote:
> While I agree with your points, they're immaterial to the
> argument I was making.  The poster to which I responded was
> arguing that "xor" didn't make sense because having it coerce
> it's arguments to booleans was "wrong".

I didn't say "wrong", I said "non-obvious".

And, with respect, the fact that you have to argue your point is evidence
in my favor. Of course "proof" would require a comprehensive survey, and I
think we can all agree this point isn't worth such effort :-)

But I do think that a bitwise operator should silently transform to a
logical operator for strings is not obvious.

What is 388488839405842L ^ "hello"?

Python says that's an "unsupported operand type(s) for ^: 'long' and
'str'". Why is it wrong?

This would also work if Python were more like C++ and we could define

xor(string, string)
xor(int, int) 

and be done with it, but in Python, there should be an obvious meaning for
int ^ string, and there isn't.

It is also true that I recommended the OP consider subclassing string to
make ^ do what he wants. But it seems to be reasonably well expected that
while user classes can do what they like with operators (as long as they
are willing to pay the sometimes-subtle prices, especially the ones
involved with poorly defining __cmp__), that the core language should not
do such things.



More information about the Python-list mailing list