[SciPy-dev] Arrays as truth values?
schofield at ftw.at
Tue Nov 8 08:21:08 CST 2005
On Mon, 7 Nov 2005, Travis Oliphant wrote:
> Steven H. Rogers wrote:
> >OK. I can't think of a really good use case for using an array as a truth
> >value. I would argue though, that it would make sense for an array of zeros
> >to be False and an array with any non-zero values to be True.
> I agree this makes sense. That's why it used to be the default
> behavior. But you can already get that behavior with any(a).
> There will be many though, I'm afraid, who think b or a ought to return
> element-wise like b | a does. This is not possible in Python. Raising
> an error will at least alert them to the problem which might otherwise
> give them misleading results.
I agree with this reasoning, but I'd like to illustrate a drawback to the
>>> 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()
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? We still have scipy.equal() and scipy.not_equal() for
This might actually cause less code breakage (like for me ;), since using
== and != in conditional expressions would work as before. 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:
>>> l1 = [1,2,3]
>>> l2 = [1,2,3]
>>> l1 == l2
>>> import array
>>> b1 = array.array('d',[1,2,3])
>>> b2 = b1
>>> b1 == b2
More information about the Scipy-dev