[SciPy-dev] Arrays as truth values?

Ed Schofield schofield at ftw.at
Wed Nov 2 16:10:13 CST 2005

Robert Cimrman wrote:

>>>numarray doesn't permit using arrays as truth values since we figured 
>>>that it wasn't very clear what people expected to happen (this case is 
>>>a good illustration). I'd like to make the argument that scipy_core 
>>>also not permit arrays to be used as truth values (i.e., one should get 
>>>an exception if one tries to use it that way). I realize that this will 
>>>break some old code, but since incompatible changes are being made, 
>>>this is the time to make this sort of change.  If left in, it is going 
>>>to bite people, often quietly.
>>I agree it can bite people, but I'm concerned that arrays not having a 
>>truth value is an odd thing in Python --- you have to implement it by 
>>raising an error when __nonzero__ is called right?
>>All other objects in Python have truth values (including its built-in 
>>array).  My attitude is that its just better to teach people the proper 
>>use of truth values, then to break form with the rest of Python.
>>I'm would definitely like to hear more opinions though.  It would be 
>>very easy to simply raise and error when __nonzero__ is called.
>Speaking about 'and' only, my problem with the current implementation of 
>it is that it _looks_ like working as '*' in some cases - 'b and c' 
>returns an array whose length is that of b and c (if the lengths are 
>equal, that is). I would not be against 'b and c' giving a single True 
>or False... But this also breaks the Python semantics of 'and'. The same 
>holds for other logical ops, of course.
>So I don't know :-) - I can live with the current state.
I'm slightly in favour of raising an exception like in nummaray.

But I'd like to point out an inconsistency between the current truth
values of ndarrays and those of other Python objects:
>>> l = [False, False]
>>> print bool(l)
>>> s = set(l)
>>> print bool(s)
>>> import array
>>> a = array.array('b',l)
>>> print bool(a)
>>> import scipy
>>> nd1 = scipy.array(l, 'b')
>>> nd2 = scipy.array(l, '?')
>>> print bool(nd1)
>>> print bool(nd2)


If we do adopt Python's strange idiom with logical operators we should
probably make arrays' truth values consistent with Python objects too.

-- Ed

More information about the Scipy-dev mailing list