[Python-Dev] Re: ANN: PEP 335: Overloadable Boolean Operators

Tim Hochberg tim.hochberg at ieee.org
Wed Sep 15 08:48:16 CEST 2004


Greg Ewing wrote:
> "Phillip J. Eby" <pje at telecommunity.com>:
> 
> 
>>For the numeric use cases, frankly I don't see why one would want to
>>apply short-circuiting boolean operators to arrays, since presumably
>>the values in them have already been evaluated.  And if the idea is
>>to make them *not* be short-circuting operators, that seems to me to
>>corrupt the whole point of the logical operators versus their
>>bitwise counterparts.
> 
> 
> 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.

Another example from numarray land. You can pick out subarrays, by 
indexing with an array of booleans, which can be pretty slick.

 >>> import numarray as na
 >>> a = na.arange(9)
 >>> a[a < 4]
array([0, 1, 2, 3])

You would like a[2 < a < 4] to work, but instead you need:

 >>> a[(2 < a) & (a < 4)]

Gregs proposal could fix this.

Or suppose you want to find the logical and of a, b. Consider trying to 
use bitwise ops:

 >>> a = na.array([1,1,1,1]) # all true
 >>> b = na.array([2,2,2,2]) # all true
 >>> a & b
array([0, 0, 0, 0]) # oops, that's why there's logical_and
 >>> na.logical_and(a,b)
array([1, 1, 1, 1], type=Bool)
 >>> (a!=0) & (b!=0) # this also works, but it does 3x as much work
array([1, 1, 1, 1], type=Bool)

Again with Greg's proposal one could write 'a and b' for this. Much nicer.

It's not that you couldn't make numarrays short circuit. In the 
expression "a and b", if all the elements of a are false, then we can 
skip evaluating b. I'm just not sure that this is a good idea.

-tim












More information about the Python-Dev mailing list