[SciPy-dev] Arrays as truth values?

Robert Kern rkern at ucsd.edu
Tue Nov 8 08:34:30 CST 2005


Ed Schofield wrote:

> I agree with this reasoning, but I'd like to illustrate a drawback to the
> new behaviour:
> 
>>>>a1 = array([1,2,3])
>>>>a2 = a1
>>>>if a1 == a2:
> 
> ...     print "equal"
> ...
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> ValueError: The truth value of an array with more than one element is
> ambiguous. Use a.any() or a.all()

It's not a drawback. This is exactly the reason we're making the change.

> Using == and != to compare arrays was simple and (I think) unambiguous
> before. It would be nice to allow these comparisons again, while raising
> an exception for the general case.  Perhaps we could modify arrays' __eq__
> and __neq__ methods to call .any() and .all() for us, returning a single
> truth value, rather than returning an array of truth values as it does
> currently? 

No. Rich comparisons were added to the language precisely *for Numeric*
so we could return arrays instead of just True or False. We're not going
to regress to the Python 2.0 era.

In any case, you can't have those methods "call .any() and .all() for
us;" there really is an ambiguity. We don't know beforehand which one
you want called. And in the face of ambiguity, we're refusing the
temptation to guess.

> We still have scipy.equal() and scipy.not_equal() for
> elementwise comparisons.
> 
> This might actually cause less code breakage (like for me ;), since using
> == and != in conditional expressions would work as before. 

I think you may need to reexamine your code that uses that construction.
The old behavior was implicitly the same as any(a1 == a2) not all(a1 ==
a2). It's likely that you wanted the latter not the former.

> It would also
> have the bonus of bringing SciPy's behaviour closer to that of Python's
> builtin objects and existing 1-d array module:

Any API compatibility with the stdlib's array module is entirely
coincidental. It's not a goal and never will be.

-- 
Robert Kern
rkern at ucsd.edu

"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter




More information about the Scipy-dev mailing list