[Numpy-discussion] Simplest ndarray subclass __new__ possible?
zpincus at stanford.edu
Mon Feb 27 21:53:02 CST 2006
I would like to put together a wiki page about writing ndarray
subclasses because this is obviously a difficult topic, and the
available documentation (e.g. looking at defmatrix) doesn't cover all
-- or even the most common -- uses.
As such, I am trying to put together a "skeleton" ndarray subclass
which has all the basic features (a __new__ that allows for direct
construction of such objects from other data objects, and porpagation
of simple attributes in __array_finalize__).
Right now I am trying to figure out what the minimum complement of
things that need to go into such a __new__ method is. Below is my
first effort, derived from defmatrix. Any help identifying parts of
this code that are unnecessary, or parts that need to be added, would
directly result in a better wiki page once I figure everything out.
> What follows is what I have so far. Have I missed anything, or can
> anything else be removed?
> class contour(numpy.ndarray):
> def __new__(subtype, data, dtype=None, copy=True):
> ##### Do I need this first if block?
> ##### Wouldn't the second block would do fine on its own?
> if isinstance(data, contour):
> dtype2 = data.dtype
> if (dtype is None):
> dtype = dtype2
> if (dtype2 == dtype) and (not copy):
> return data
> return data.astype(dtype)
> if isinstance(data, numpy.ndarray):
> if dtype is None:
> intype = data.dtype
> intype = numpy.dtype(dtype)
> new = data.view(contour)
> if intype != data.dtype:
> return new.astype(intype)
> if copy: return new.copy()
> else: return new
> # now convert data to an array
> arr = numpy.array(data, dtype=dtype, copy=copy)
> ##### Do I need this if block?
> if not (arr.flags.fortran or arr.flags.contiguous):
> arr = arr.copy()
> ##### Do I need the fortran flag?
> ret = numpy.ndarray.__new__(subtype, arr.shape, arr.dtype,
> buffer=arr, fortran=arr.flags.fortran)
> return ret
More information about the Numpy-discussion