[Numpy-discussion] Simplest ndarray subclass __new__ possible?

Zachary Pincus zpincus at stanford.edu
Mon Feb 27 08:50:10 CST 2006


On Feb 27, 2006, at 5:06 AM, Colin J. Williams wrote:
> [snip]
> Would there be any merit in breaking this into two parts, __new__  
> to allocate space and __init__ to initialize the data?

What I presented below is exactly the __new__ grabbed from the matrix  
class definition in defmatrix.py (less matrix-specific stuff). I  
assume it's overkill for what I need, but it seemed like a good  
starting place. Figuring out what bits are really necessary and what  
bits aren't would be step 1, before I can even think about whether  
some of the bits should really live in __init__ (though I can't  
actually see any of the below lining in init, because most of the  
code is given over to deciding whether or not to allocate space).

Zach

> Zachary Pincus wrote:
>>
>> What follows is what I have so far. Have I missed anything, or  
>> can  anything else be removed?
>>
>> Zach
>>
>> 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
>>       else:
>>         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
>>
>>
> Would there be any merit in breaking this into two parts, __new__  
> to allocate space and __init__ to initialize the data?
>
> Colin W.
>
>
>
> -------------------------------------------------------
> This SF.Net email is sponsored by xPML, a groundbreaking scripting  
> language
> that extends applications into web and mobile media. Attend the  
> live webcast
> and join the prime developer group breaking into this new coding  
> territory!
> http://sel.as-us.falkag.net/sel? 
> cmd=lnk&kid=110944&bid=241720&dat=121642
> _______________________________________________
> Numpy-discussion mailing list
> Numpy-discussion at lists.sourceforge.net
> https://lists.sourceforge.net/lists/listinfo/numpy-discussion





More information about the Numpy-discussion mailing list