[Numpy-discussion] basearray / arraykit

Tim Hochberg tim.hochberg at cox.net
Wed May 10 14:47:01 EDT 2006


Sasha wrote:

> On 5/8/06, Tim Hochberg <tim.hochberg at cox.net> wrote:
>
>> [...] Here's a brief example;
>> this is what an custom array class that just supported indexing and
>> shape would look like using arraykit:
>>
>>     import numpy.arraykit as _kit
>>
>>     class customarray(_kit.basearray):
>>         __new__ = _kit.fromobj
>>         __getitem__ = _kit.getitem
>>         __setitem__ = _kit.setitem
>>         shape = property(_kit.getshape, _kit.setshape)
>
>
> I see the following problem with your approach: customarray.__new__ is
> supposed to return an instance of customarray, but in your example it
> returns a basearray.

Actually, it doesn't.  The signature of fromobj is: fromobj(subtype, 
obj, dtype=None, order="C"). It returns an object of type subtype (as 
long as subtype is derived from basearray). At present, fromobj is 
implemented in Python as:

    def fromobj(subtype, obj, dtype=None, order="C"):
        if order not in ["C", "FORTRAN"]:
            raise ValueError("Order must be either 'C' or 'FORTRAN', not
    %r" % order)
        nda = _numpy.array(obj, dtype, order=order)
        return basearray.__new__(subtype, nda.shape, nda.dtype,
    nda.data, order=order)

That's kind of kludgy, and I plan to remove the dependance on 
numpy.array at some point, but it seems to work OK.

> You may like an approach that I took in writing
> r.py <https://svn.sourceforge.net/svnroot/rpy/trunk/sandbox/r.py>.  In
> the context of your example, I would make fromobj a classmethod of
> _kit.basearray and use the type argument to allocate the new object
> (type->tp_alloc(type, 0);).   This way customarray(...) will return
> customarray as expected.
>
> All _kit methods that return arrays can take the same approach and
> become classmethods of _kit.basearray.  The drawback is the pollution
> of the base class namespace, but this may be acceptable if you name
> the baseclass methods with a leading underscore.

I'd rather avoid that since one of my goals is to remove name polution. 
I'll keep it in mind though if I run into problems with the above approach.

-tim







More information about the NumPy-Discussion mailing list