[Numpy-discussion] 0-D arrays as scalars

Travis Oliphant oliphant.travis at ieee.org
Mon Jun 10 11:13:07 EDT 2002


On Mon, 2002-06-10 at 11:08, Konrad Hinsen wrote:
> "eric jones" <eric at enthought.com> writes:
> 
> 
> > I think the only reason for the silent conversion is that Python lists
> > only allow integer values for use in indexing so that:
> 
> There are some more cases where the type matters. If you call C
> routines that do argument parsing via PyArg_ParseTuple and expect a
> float argument, a rank-0 float array will raise a TypeError. All the
> functions from the math module work like that, and of course many in
> various extension modules.

Actually, the code in PyArg_ParseTuple asks the object it gets if it
knows how to be a float.  0-d arrays for some time have known how to be
Python floats.  So, I do not think this error occurs as you've
described.  Could you demonstrate this error?

In fact most of the code in Python itself which needs scalars allows
arbitrary objects provided the object has defined functions which return
a Python scalar.  

The only exception to this that I've seen is the list indexing code
(probably for optimization purposes).   There could be more places, but
I have not found them or heard of them.  

Originally Numeric arrays did not define appropriate functions for 0-d
arrays to act like scalars in the right places.  For quite a while, they
have now.  I'm quite supportive of never returning Python scalars from
Numeric array operations unless specifically requested (e.g. the
toscalar method).  

> > On coercion rules:
> > 
> > As for adding the array to a scalar value, 
> > 
> >   x = array([3., 4.], Float32)
> >   y = x + 1.
> > 
> > Should y be a Float or a Float32?  I like numarray's coercion rules
> > better (Float32).  I have run into this upcasting to many times to
> 
> Statistically they probably give the desired result in more cases. But
> they are in contradiction to Python principles, and consistency counts
> a lot on my value scale.
> 
> I propose an experiment: ask a few Python programmers who are not
> using NumPy what type they would expect for the result. I bet that not
> a single one would answer "Float32".
> 

I'm not sure I agree with that at all.  On what reasoning is that
presumption based?  If I encounter a Python object that I'm unfamiliar
with, I don't presume to know how it will define multiplication. 







More information about the NumPy-Discussion mailing list