[Numpy-discussion] subclassing ndarray subtleties??

Tom Aldcroft aldcroft at head.cfa.harvard.edu
Mon May 21 13:47:56 EDT 2012

Over on the scipy-user mailing list there was a question about
subclassing ndarray and I was interested to see two responses that
seemed to imply that subclassing should be avoided.

>From Dag and Nathaniel, respectively:

"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..."

So my question is whether there are subtleties or issues that are not
covered in the standard NumPy documents on subclassing ndarray.  What
are the "things you can't do etc"?  I'm working on a project that
relies heavily on an ndarray subclass which just adds a few attributes
and slightly tweaks __getitem__.  It seems fine and I really like that
the class is an ndarray with all the built-in methods already there.
Am I missing anything?

>From the scipy thread I did already learn that one should also
override __getslice__ in addition to __getitem__ to be safe.


More information about the NumPy-Discussion mailing list