[Numpy-discussion] Re: The idiom for supporting matrices and arrays in a function

Travis Oliphant oliphant at ee.byu.edu
Wed Mar 1 17:10:38 CST 2006

Robert Kern wrote:

>Bill Baxter wrote:
>>The NumPy for Matlab Users's wiki is currently pleading to have someone
>>fill in  "/*the idiom for supporting both matrices and arrays in a
>>* /Does anyone know what this is?
>The subclassing functionality is rather new, so I don't know if the proper
>idioms have really been discovered. I would suggest converting to arrays using
>asarray() right at the beginning of the function. If you want to spit out
>matrices/what-have-you out again, then you will need to do some more work. I
>would suggest looking at the procedure that ufuncs do with __array_finalize__
>and __array_priority__ and creating a pure Python reference implementation that
>others could use. It's possible that you would be able to turn it into a decorator.
This is kind of emerging as the right strategy (although it's the 
__array_wrap__ and __array_priority__ methods that are actually relevant 
here.  But, it is all rather new so we can forgive Robert this time ;-) )

The __array_priority__ is important if you've got "competing" wrappers 
(i.e. a 2-input, 1-output function) and don't know which __array_wrap__ 
to use for the output.

In matlab you have one basic type of object.    In NumPy you have a 
basic ndarray object that can be sub-classed which gives rise to all 
kinds of possibilities.  I think we are still figuring out what the best 
thing to do is.

Ufuncs convert everything to base-class arrays (what asarray does) and 
then use the __array_wrap__ of the input with the highest 
__array_priority__ to wrap all of the outputs (except that now output 
arrays passed in use their own __array_wrap__).

So, I suppose following their example is a reasonable approach.

Look in numpy/linlag/linlag.py for examples of using the 
asarray/__array_wrap__ strategy...

The other approach is to let sub-classes through the array conversion 
(asanyarray), but this approach could rise to later errors if the 
sub-class redefines an operation you didn't expect it to, so is probably 
not safe unless all of your operations are functions that can handle any 
array subclass.

And yes, I think a decorator could be written that would manage this.  
I'll leave that for the motivated...


More information about the Numpy-discussion mailing list