[Numpy-discussion] C extensions: is Py_XDECREF() needed when using PyArray_FromAny()

Travis Oliphant oliphant.travis at ieee.org
Mon Jul 24 14:29:15 CDT 2006

Sebastian Haase wrote:
> Hi,
> I'm converting SWIG typemap'ed C extensions from numarray to numpy.
> I studied (and use parts of) numpy.i from the doc directory.
> I noticed that there is no
> decref  for the  TYPEMAP_INPLACE2 typemap. This uses a function
> obj_to_array_no_conversion() which in turn just returns
> the original PyObject* ( casted to a PyArrayObject* after some sanity 
> checks)  It looks to me that in this case there should be an explicit
> Py_INCREF()  - in case the function is threaded (releases the Python 
> GIL) since it holds a pointer to that object's data .

Probably, true.  The numpy.i typemaps are not thoroughly reference-count 

> (Alternatively) Travis suggested (at the 
> http://www.scipy.org/Converting_from_numarray wiki page) using
> PyArray_FromAny  - is this incrementing the ref.count (implicitely) ? 
> The numarray equivalent (NA_InputArray) IS incrementing the ref.count 
> (as far as I know...).

Yes, you get back a new reference from PyArray_FromAny.

> Furthermore on that same wiki page the  PyArray_FromAny() is called 
> together with PyArray_DescrFromType(<type>).
> After searching through the numpy source I found that in
> blasdot/_dotblas.c  (in dotblas_matrixproduct() )there is an explicit 
> Py_INCREF even on the dtype returned from PyArray_DescrFromType.

PyArray_FromAny consumes a reference to the PyArray_Descr * object 
(which is a Python object).  Thus, because PyArray_FromAny is called 
twice with the same data-type object, there is a need to increment it's 
reference count.


More information about the Numpy-discussion mailing list