Python Type Extension w/ Numpy Array Reference Count Behavior

588 Views Asked by At

I am writing a C extension for a new python Type. One of the attributes for this new type will be a Numpy array that comes from external data passed into the C extension. I define the attribute array like this:

array = PyArray_SimpleNewFromData(numDims,shape,NPY_DOUBLE,[DATA POINTER])

with [DATA POINTER] being the location of the external data in memory.

I then use this command to set the array attribute's "base" to the type object that contains the attribute:

PyArray_SetBaseObject((PyArrayObject*)array,(PyObject*)[PY_TYPE OBJECT])

Now, to the best of my understanding, when I import my module, the "type" of object.array is numpy.ndarray.

When I take a normal ndarray and preform the following commands, I see the subsequent behavoir:

>>>import numpy as np
>>>import sys
>>>base = np.array([1,2,3,4,5])
>>>sys.getrefcount(base)
2
>>>newArr = base
>>>sys.getrefcount(base)
3
>>>del newArr
>>>sys.getrefcount(base)
2

I want my array attribute to increment and decrement its base's reference count just like newArr incremented and then decremented base's reference count. However, my module behaves like this:

>>>from myModule import myObj
>>>import sys
>>>base = myObj()
>>>sys.getrefcount(base)
2
>>>newArr = base.array
>>>sys.getrefcount(base)
2
>>>del newArr
>>>sys.getrefcount(base)
2

Does anyone know how I can get use of my array attribute to alter the reference count of my base type object? My original thought was to use this numpy ndarray behavior, but I am open to comments and suggestions!

0

There are 0 best solutions below