[Numpy-discussion] suggestion for generalizing numpy functions

Darren Dale dsdale24 at gmail.com
Mon Jul 13 17:18:27 EDT 2009


I've put together a first cut at implementing __array_prepare__, which
appears to work, and I would like to request feedback. Here is an overview
of the approach:

Once the ufunc machinery has created the output arrays, it is time to offer
subclasses a chance to initialize the output arrays and determine metadata
and/or perform whatever other operations may be desired before the ufunc
actually performs the computation. In the construct_arrays function in
umath.c, I added a function _find_array_prepare, which attempts to find an
__array_prepare__ method to call from the inputs, almost identical to the
existing _find_array_wrap.

The default implementation of __array_prepare__ is currently identical to
the default implementation of __array_wrap__, in methods.c. I think that bit
of code fits better in __array_prepare__, but maybe there is a good reason
to keep it in __array_wrap__ and make the default __array_prepare__ just
pass through the output array.

So now that the output arrays have been created by the ufunc machinery, and
those arrays have been initialized by __array_prepare__ (which has the same
call signature as __array_wrap__), the ufunc can continue as usual. Classes
that already rely on __array_wrap__ can continue to do so, implementing
__array_prepare__ is entirely optional. But other classes like MA and
Quantity can set the output array type, determine a mask, perform units
analysis checks, and update some metadata in advance of the ufunc, and they
can still update metadata after the ufunc using __array_wrap__.

The implementation is included in the attached patch. I ran np.test and got
1 known failure and 11 skipped tests. I am using a quantities branch for
testing (bzr branch
lp:~dsdale24/python-quantities/quantities-array-prepare), and after simply
moving my units analysis out of __array_wrap__ and into __array_prepare__,
quantities.test() does not yield any errors.

Darren
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20090713/7a922570/attachment.html>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: array_prepare.patch
Type: application/octet-stream
Size: 8184 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20090713/7a922570/attachment.obj>


More information about the NumPy-Discussion mailing list