[Python-Dev] ANN: PEP 335: Overloadable Boolean Operators
James Y Knight
foom at fuhm.net
Wed Sep 15 08:33:50 CEST 2004
On Sep 15, 2004, at 12:34 AM, Greg Ewing wrote:
> There's more to it than short-circuiting. Consider
>
> a = array([42, ""])
> b = array([(), "spam"])
>
> One might reasonably expect the result of 'a or b' to
> be
>
> array([42, "spam"])
>
> which is considerably different from a bitwise operation.
One might, but *I* would reasonably expect it to give me array a, by
extrapolation from every other data type in python.
Consider also this:
x and 4 or 5
which is of course a common idiom to workaround the lack of an
if-then-else expression.
So, try with x = array([42, 0])
Currently, doing this with numarray raises an exception "An array
doesn't make sense as a truth value. Use sometrue(a) or alltrue(a).".
Odd, since nearly all python objects can somehow be turned into a truth
value, but ok. [Forbidding __nonzero__ prevents horrible mistakes from
occurring because of the misuse of the comparison operators as
element-wise comparison. "if array([1,2,3]) == array([3,2,1]): print
'Bad'" of course oughtn't print 'Bad'.]
However, with this change, it may instead return:
array([4, 5])
and that's nothing like what was meant.
The idiom would change to:
bool(x) and 4 or 5
I suppose...
James
PS: Perl6 has distinct element-wise operators ("hyper" operators). I
find that less distasteful than misusing regular operators as
element-wise operators, when they really have vastly different
semantics.
More information about the Python-Dev
mailing list