[Numpy-discussion] should I replace asarray with asanyarray in my code ?

Travis Oliphant oliphant.travis at ieee.org
Wed Sep 27 20:04:50 CDT 2006

Sebastian Haase wrote:
> Hi,
> This is a vaguely formulated question ...
> When I work with memmap'ed files/arrays I have a derived class 
> that adds special attributes to the array class (referring to the MRC image 
> file format used in medical / microscopy imaging)
> What are the pros and cons for asarray() vs. asanyarray()
> One obvious con for asanyarray is that its longer and asarray is what I have 
> been using for the last few years  ;-)

asarray() guarantees you have a base-class array.  Thus, you are not 
going to be thwarted by an re-definitions of infix operators, or other 
changed methods or attributes which you might use in your routine.

asanyarray() allows a simple way of making sure your function returns 
any sub-class so that, for example, matrices are passed seamlessly 
through your function (matrix in and matrix out).

However, a big drawback of asanyarray is that you must be sure that the 
way your function is written will not get confused by how a sub-class 
may overwrite the array methods and attributes.   This significantly 
limits the application of asanyarray in my mind, as it is pretty 
difficult to predict what a sub-class *might* do to it's methods 
(including the special methods implementing the infix operators). 

A better way to write a function that passes any sub-class is to use 
asarray() so you are sure of the behavior of all methods and "infix" 
operators and then use the __array_wrap__ method of the actual input 
arguments (using __array_priority__ to choose between competing input 
objects).  I expect that a decorator that automates this process will be 
added to NumPy eventually.   Several examples have already been posted 
on this list.

After getting the array result, you call the stored __array_wrap__ 
function which will take a base-class ndarray and return an object of 
the right Python-type (without copying data if possible).  This is how 
the ufuncs work and why they can take sub-classes (actually anything 
with an __array__ method) and the same kind of object.


More information about the Numpy-discussion mailing list