[Numpy-discussion] The array interface published

David M. Cooke cookedm at physics.mcmaster.ca
Mon Apr 4 21:17:19 EDT 2005


Michiel Jan Laurens de Hoon <mdehoon at ims.u-tokyo.ac.jp> writes:

> Travis Oliphant wrote:
>>> Some comments on the array interface:
>>>
>>> 1) The "__array_shape__" method is identical to the existing
>>> "shape" method in Numerical Python and numarray (except that
>>> "shape" does a little bit better checking, but it can be added
>>> easily to "__array_shape__"). To avoid code duplication, it might
>>> be better to keep that method. (and rename the other methods for
>>> consistency, if desired).
>> There is no code duplication.  In these cases it is just another
>> name for .shape.    What "better checking" are you referring to?
>
> The method __array_shape__ is
>
>      if (strcmp(name, "__array_shape__") == 0) {
>          PyObject *res;
>          int i;
>          res = PyTuple_New(self->nd);
>          for (i=0; i<self->nd; i++) {
>              PyTuple_SET_ITEM(res, i, PyInt_FromLong((long)self->dimensions[i]));
>          }
>          return res;
>      }
>
> while the method shape is
>
>      if (strcmp(name, "shape") == 0) {
>          PyObject *s, *o;
>          int i;
>
>          if ((s=PyTuple_New(self->nd)) == NULL) return NULL;
>
>          for(i=self->nd; --i >= 0;) {
>              if ((o=PyInt_FromLong(self->dimensions[i])) == NULL) return NULL;
>              if (PyTuple_SetItem(s,i,o) == -1) return NULL;
>          }
>          return s;
>      }
>
> so it checks if PyInt_FromLong and PyTuple_SetItem are successful. I
> don't see how PyTuple_SetItem can fail, so PyTuple_SET_ITEM should be
> fine.

The #1 rule of thumb when using the Python C API: _always_ check your
returned results (this usually means checking for NULL). In this,
PyInt_FromLong _can_ fail (if there's an error creating the int free
list). I've fixed this in CVS.

You're right on PyTuple_SET_ITEM: the space for it is guaranteed to
exist after the PyTuple_New.

-- 
|>|\/|<
/--------------------------------------------------------------------------\
|David M. Cooke                      http://arbutus.physics.mcmaster.ca/dmc/
|cookedm at physics.mcmaster.ca




More information about the NumPy-Discussion mailing list