[Numpy-discussion] Subclassing ndarray in Pyrex

Pierre GM pgmdevlist at gmail.com
Wed Jan 31 06:15:05 CST 2007


I'm still trying to subclass ndarray in Pyrex, without much success so far.

I started to follow Francesc's suggestion 
(http://projects.scipy.org/pipermail/numpy-discussion/2007-January/025644.html), 
but that doesn't fit what I need: the myarray class Francesc introduced is 
just an object, not a subclass of ndarray...

The closest I came to something vaguely running is the following (called 
subnd.pyx later on):
#-------------------
from definitions cimport import_array, \
     malloc, free, npy_intp, \
     PyArray_GETITEM, PyArray_EMPTY, \
     ndarray, dtype

# NumPy must be initialized
import_array()

import numpy as _N
cdef class Sub_2(ndarray):
    cdef readonly object _info
    cdef ndarray __mask
    
    def __new__(self, object shape=None, object dtype=None, object 
buffer=None, 
                object order=None, object infodict={}):
        self.__mask = <ndarray>_N.zeros(shape, _N.bool)
        self._info = infodict
        return
  
    property info:
        def __get__(self):
            return self._info
        def __set__(self, value):
            self._info = value
    property _mask:
        def __get__(self):
            return self.__mask


def subarray(obj, info={}):
    _obj = <ndarray>_N.asarray(obj)
    print "_obj is: %s" % _obj
    _internal = Sub_2(shape=_obj.shape, dtype=_obj.dtype)
    _internal.flat[:] = _obj.flat[:]
    _internal.info = info
    return _internal    
#----------------------
However, I get a segfault when I try to play with it in Python:
>>> import numpy as N
>>> import subnd
>>> L = N.array([1,2,3]
>>> x = subarray(L)
>>> x
Sub_2([1, 2, 3])
>>> x+1
Sub_2([2, 3, 4])
>>> N.log(x)
crash
        
So obviously I'm missing something, but what ? Some kind of closure ?

Moreover, I'm a bit disappointed with this method: if I understand correctly 
the subtleties of subclassing in pyrex, the ndarray.__new__ is called before 
Sub_2.__new__, with the same arguments. As ndarray.__new__  doesn't take 
optional arguments, the subclass can't either. That's a bit limiting, I have 
to call the constructor function all the time...


I'm completely at loss, here. Any advice/help/suggestions would be more than 
welcome.


More information about the Numpy-discussion mailing list