[Numpy-discussion] ndarray: subclassing a subclass looses custom attribute

Sebastian Haase seb.haase@gmail....
Fri Oct 1 06:03:53 CDT 2010

On Fri, Oct 1, 2010 at 12:38 PM, Pierre GM <pgmdevlist@gmail.com> wrote:
> On Oct 1, 2010, at 11:26 AM, Sebastian Haase wrote:
>> Hi,
>> I'm trying to add a 'meta' attribute to ndarray to keep track of image
>> data filenames and resolution etc.
>> Following  the excellent document
>> http://docs.scipy.org/doc/numpy/user/basics.subclassing.html
>> this worked right away.
>> However, I had done this before for some specific image-file-types:
>> those would add there own attribute to ndarray array (e.g. arr.Mrc)
>> Now if I call the new  ndarray_meta on my ndarray_with_mrc I loose the
>> `Mrc` attribute, leaving only the new `meta` attribute.
>> My code is essentially a verbatim copy of
>> http://docs.scipy.org/doc/numpy/user/basics.subclassing.html#simple-example-adding-an-extra-attribute-to-ndarray
>> What can I do ?
> Post your code, so that we can see what you actually did.
> If I had to guess, I'd say you forgot to define your 'Mrc' attribute in your ndarray_meta.__array_finalize__. But once again, without some code, it's only a guess.

class ndarray_inMrcFile(ndarray):
    def __new__(cls, input_array, mrcInfo=None):
        obj = asanyarray(input_array).view(cls)
        obj.Mrc = mrcInfo
        return obj

    def __array_finalize__(self, obj):
        if obj is None: return
        self.Mrc = getattr(obj, 'Mrc', None)

class ndarray_meta(ndarray):
    def __new__(cls, input_array, meta=None):
        obj = asanyarray(input_array).view(cls)
        obj.meta = nd_meta_attribute( meta )
        return obj

    def __array_finalize__(self, obj):
        if obj is None: return
        self.meta = getattr(obj, 'meta', nd_meta_attribute())

So, ndarray_meta is (like ndarray_inMrcFile) derived from ndarray; not
one from the other, because ndarray_meta is supposed to be generic and
ndarray_inMrcFile is just one example of a ndarray derived class.

Thanks for looking at this
-- Sebastian

More information about the NumPy-Discussion mailing list