[Numpy-discussion] subclassing ndarray and recarray

Bernhard Voigt bernhard.voigt at gmail.com
Wed May 9 08:54:37 EDT 2007


I'm trying to subclass ndarray or recarray to build a record array that has
a dictionary with a mapping of keys to array indexes and vice versa. I come
across the problem, that depending on the field access method I get
different types back:

# a is a sublcass of record array
>> print type(a)
<class 'myrecarray'>

>> print type(a['x'])
<class 'myrecarray'>

>> print type(a.x)
<type 'numpy.ndarray'>

I guess this has something to do with the call to the view method in the
recarray implementation but I can't figure out how to solve this. Hence I
switched back to subclass the ndarray and implemented the field access via
a.x by myself.

In order to update the mapping of the array instance when slicing is used, I
would like to get the selected indexes in the __array_finalize__ method. Is
there a way to access the selected indexes, or do I have to overwrite the
__getitem__ method to get indexes from the slice object. This could be
rather complicated due to the many different slice specifications.

Here's an incomplete code example from my subclass, maybe this helps to
understand the problem:

def __array_finalize__(self, obj):
        if not hasattr(self, 'mapping'):
            # create a mapping for the selected indexes from the mapping of
the original array given by obj
            # reverse_mapping maps indexes to keys, __selected_indexes is
the field I would like to have
            self.reverse_mapping = dict((obj.reverse_mapping[i], i for i n
self.__selected_indexes)
            self.mapping = dict((k,i) for i,k in
self.reverse_mapping.iteritems())

def __getitem__(self, key):
        # fill the __selected_indexes field
        self.__selected_indexes = foo(key)
        # pass the selection to ndarray - calls __array_finalilze__ and
where the mapping is performed
       return numpy.ndarray.__getitem__(self, key)

Thanks for help! Bernhard
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20070509/6df84af0/attachment.html>


More information about the NumPy-Discussion mailing list