[Numpy-discussion] Inconsistency with __index__() for rank-1 arrays?

Pauli Virtanen pav at iki.fi
Fri Oct 29 06:59:04 EDT 2010


pe, 2010-10-29 kello 12:48 +0200, Francesc Alted kirjoitti:
> A Friday 29 October 2010 12:18:20 Pauli Virtanen escrigué:
> > Fri, 29 Oct 2010 09:54:23 +0200, Francesc Alted wrote:
> > [clip]
> > 
> > > My vote is +1 for deprecating ``array([scalar])`` as a scalar index
> > > for NumPy 2.0.
> > 
> > I'd be -0 on this, since 1-element Numpy arrays function like scalars
> > in several other contexts, e.g. in casting to Python types and in
> > boolean context.
> > 
> > Note also that at least Python's struct module (mis-?)uses
> > __index__() for casting inputs to integers.
> 
> Uh, could you put some examples of this please?

Sure:

	if array([[1]]):
	    print "OK"

	x = float(array([[1]]))

and for the second point, in Python/Modules/_struct.c:

     95 static PyObject *
     96 get_pylong(PyObject *v)
     97 {
     98     assert(v != NULL);
     99     if (!PyLong_Check(v)) {
    100         /* Not an integer;  try to use __index__ to convert. */
    101         if (PyIndex_Check(v)) {

        >>> import numpy as np, struct
        >>> struct.pack("i", np.array([1]))
        '\x01\x00\x00\x00'

-- 
Pauli Virtanen




More information about the NumPy-Discussion mailing list