[SciPy-dev] Arrays as truth values?
perry at stsci.edu
Mon Nov 7 15:32:19 CST 2005
On Nov 7, 2005, at 8:20 AM, Steven H. Rogers wrote:
> Concur that allowing arrays as truth values is the pythonic thing to
> Please do it as long as it's documented.
> Travis Oliphant wrote:
>> 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
>> 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.
I guess I'd like to challenge the pythonicity of always having truth
values. The situation here may be unique (so far, I'm not aware of any
other similar cases). When Python allowed rich comparisons, it meant
such comparisons didn't have to return simple boolean values. It was
implemented almost entirely to satisfy Numeric users. This lead to many
users believing that the results of such comparisons could now be used
with "and" and "or" since as far as they were concerned, the results
did result in booleans (arrays, of course).
My argument is that because of this mismatch we can be *sure* that many
users will try to use arrays this way, regardless of how many warnings
you put in the documentation. And the vast majority of the time, they
will not get what they intended. And for many of these cases, that
there was a mistake may not surface right away (they are going to get
as a result an array, usually of the right shape, if not the right
type). For me this is a very big drawback.
Let's look at the other side. Is it obvious what arrays are false? The
pythonic thing would to make them false if they could be empty. And
sure, they can be. But that is a pretty rare case of usage. Who is
going to use that case very often? Besides, with rank-0 values, then
people would think the pythonic thing is to treat them as false, but
they aren't empty. But some might think they should be false if all
values are 0 (the current Numeric behavior). This case would at least
be used practically, but it is at odds with how lists and other
Essentially, my argument is that this case presents many likely
surprises for users and when there isn't one obvious way to do it, it
shouldn't be done. I'd argue that not allowing arrays as truth values
it is more Pythonic. (Existing arrays don't support rich comparisons,
and they are false only when empty, as would be expected).
Does anyone else have examples that use rich comparisons to produce
sequences in other libraries that are treated as truth values?
More information about the Scipy-dev