Coding style

David M. Cooke cookedm+news at physics.mcmaster.ca
Tue Jul 18 16:58:27 EDT 2006


cookedm+news at physics.mcmaster.ca (David M. Cooke) writes:
>
> Bruno's already mentioned that iterators and generators aren't
> sequences. Numpy arrays act like the other sequence types:
>
>>>> a = numpy.array([])
>>>> a
> array([], dtype=int64)
>>>> len(a)
> 0
>>>> bool(a)
> False
>
> (0-dimensional numpy arrays are pathological anyways)

*cough* as a Numpy developer I should know better. Numpy arrays that
have more than one element don't work in a boolean context:

>>> a = numpy.array([1,2])
>>> bool(a)
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()

The reason for this is that it really was a common source of errors,
because of the rich comparision semantics used. If a and b are numpy
arrays, 'a == b' is an array of booleans.

Numpy arrays of one element act like scalars in boolean contexts:

>>> a = numpy.array([0])
>>> bool(a)
False
>>> a = numpy.array([1])
>>> bool(a)
True

(this is partly because we define a comphensive hierarchy of scalar
types to match those available in C).

-- 
|>|\/|<
/--------------------------------------------------------------------------\
|David M. Cooke
|cookedm(at)physics(dot)mcmaster(dot)ca



More information about the Python-list mailing list