[SciPy-User] subclassing ndarray : i want slice to return ndarray, not subclass

Nathaniel Smith njs at pobox.com
Mon May 21 08:15:24 EDT 2012


On Mon, May 21, 2012 at 12:42 PM, Dag Sverre Seljebotn
<d.s.seljebotn at astro.uio.no> wrote:
> On 05/21/2012 11:56 AM, pierre puiseux UPPA wrote:
>> Hello,
>> all my question is in the title. More precisely, like in scipy doc i try
>> this :
>> ======================================
>> importsys
>> import numpy as np
>>
>> class ArrayChild(np.ndarray):
>
> Subclassing ndarray is a very tricky business -- I did it once and
> regretted having done it for years, because there's so much you can't do
> etc.. You're almost certainly better off with embedding an array as an
> attribute, and then forward properties etc. to it.

Yes, it's almost always the wrong thing...

> But your answer: You want to override __getitem__, __getslice__ is
> deprecated in Python.

You have to override both, actually. After overriding __getitem__, then add
  def __getslice__(self, i, j):
    return self.__getitem__(slice(i, j))
or otherwise your __getitem__ will get skipped in some cases.

The other option would be to just accept that your subclass will be
returned from slices. If the only difference between your subclass and
the base ndarray is that your arrays have an extra ".info" attribute,
then you can just not define __array_finalize__ and check for the
presence of a ".info" attribute instead of checking for the subclass
directly. This depends on what your subclass is actually supposed to
do, obviously.

-- Nathaniel



More information about the SciPy-User mailing list