diff options
-rw-r--r-- | doc/release/1.4.0-notes.rst | 13 | ||||
-rw-r--r-- | numpy/core/src/multiarray/methods.c | 25 | ||||
-rw-r--r-- | numpy/doc/subclassing.py | 4 |
3 files changed, 40 insertions, 2 deletions
diff --git a/doc/release/1.4.0-notes.rst b/doc/release/1.4.0-notes.rst index e2df0322d..849b429cb 100644 --- a/doc/release/1.4.0-notes.rst +++ b/doc/release/1.4.0-notes.rst @@ -10,6 +10,19 @@ Highlights New features ============ +Extended array wrapping mechanism for ufuncs +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +An __array_prepare__ method has been added to ndarray to provide subclasses +greater flexibility to interact with ufuncs and ufunc-like functions. ndarray +already provided __array_wrap__, which allowed subclasses to set the array type +for the result and populate metadata on the way out of the ufunc (as seen in +the implementation of MaskedArray). For some applications it is necessary to +provide checks and populate metadata *on the way in*. __array_prepare__ is +therefore called just after the ufunc has initialized the output array but +before computing the results and populating it. This way, checks can be made +and errors raised before operations which may modify data in place. + Automatic detection of forward incompatibilities ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/numpy/core/src/multiarray/methods.c b/numpy/core/src/multiarray/methods.c index de99ca137..8ec256105 100644 --- a/numpy/core/src/multiarray/methods.c +++ b/numpy/core/src/multiarray/methods.c @@ -756,6 +756,31 @@ array_cast(PyArrayObject *self, PyObject *args) static PyObject * +array_preparearray(PyArrayObject *self, PyObject *args) +{ + PyObject *arr; + PyObject *ret; + + if (PyTuple_Size(args) < 1) { + PyErr_SetString(PyExc_TypeError, + "only accepts 1 argument"); + return NULL; + } + arr = PyTuple_GET_ITEM(args, 0); + if (arr == NULL) { + return NULL; + } + if (!PyArray_Check(arr)) { + PyErr_SetString(PyExc_TypeError, + "can only be called with ndarray object"); + return NULL; + } + Py_INCREF(arr); + return arr; +} + + +static PyObject * array_wraparray(PyArrayObject *self, PyObject *args) { PyObject *arr; diff --git a/numpy/doc/subclassing.py b/numpy/doc/subclassing.py index 5f658d922..24f0108d7 100644 --- a/numpy/doc/subclassing.py +++ b/numpy/doc/subclassing.py @@ -420,8 +420,8 @@ So: .. _array-wrap: -``__array_wrap__`` for ufuncs ------------------------------ +``__array_prepare__`` and ``__array_wrap__`` for ufuncs +------------------------------------------------------- ``__array_wrap__`` gets called at the end of numpy ufuncs and other numpy functions, to allow a subclass to set the type of the return value |