Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 25 additions & 9 deletions doc/source/reference/arrays.classes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ NumPy provides several hooks that classes can customize:

.. versionadded:: 1.13

.. note:: The API is `provisional
<https://docs.python.org/3/glossary.html#term-provisional-api>`_,

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, this doesn't render correctly. Maybe the link cannot be split across lines, or maybe github has a problem. We can allow long lines for links if needed.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's strange: I did try make html and it looked OK:
spectacle i11318

i.e., we do not yet guarantee backward compatibility.

Any class, ndarray subclass or not, can define this method or set it to
:obj:`None` in order to override the behavior of NumPy's ufuncs. This works
quite similarly to Python's ``__mul__`` and other binary operation routines.
Expand Down Expand Up @@ -70,8 +74,11 @@ NumPy provides several hooks that classes can customize:
raised.

.. note:: In addition to ufuncs, :func:`__array_ufunc__` also
overrides the behavior of :func:`numpy.dot` and :func:`numpy.matmul`
even though these are not ufuncs.
overrides the behavior of :func:`numpy.dot` and :func:`numpy.matmul`.
This even though these are not ufuncs, but they can be thought of as
:ref:`generalized universal functions<c-api.generalized-ufuncs>`
(which are overridden). We intend to extend this behaviour to other
relevant functions.

Like with other methods in python, such as ``__hash__`` and
``__iter__``, it is possible to indicate that your class does *not*
Expand All @@ -92,17 +99,26 @@ NumPy provides several hooks that classes can customize:
:class:`ndarray` will unconditionally return :obj:`NotImplemented`,
so that your reverse methods will get called.

.. note:: If you subclass :class:`ndarray`, we strongly recommend
that you avoid confusion by neither setting
:func:`__array_ufunc__` to :obj:`None`, which makes no
sense for an array subclass, nor by defining it and also defining
reverse methods, which methods will be called by ``CPython`` in
preference over the :class:`ndarray` forward methods.
.. note:: If you subclass :class:`ndarray`:

- We strongly recommend that you avoid confusion by neither setting
:func:`__array_ufunc__` to :obj:`None`, which makes no sense for
an array subclass, nor by defining it and also defining reverse
methods, which methods will be called by ``CPython`` in
preference over the :class:`ndarray` forward methods.
- :class:`ndarray` defines its own :func:`__array_ufunc__`, which
corresponds to ``getattr(ufunc, method)(*inputs, **kwargs)``. Hence,
a typical override of :func:`__array_ufunc__` would convert any
instances of one's own class, pass these on to its superclass using
``super().__array_ufunc__(*inputs, **kwargs)``, and finally return
the results after possible back-conversion. This practice ensures
that it is possible to have a hierarchy of subclasses. See
:ref:`Subclassing ndarray <basics.subclassing>` for details.

.. note:: If a class defines the :func:`__array_ufunc__` method,
this disables the :func:`__array_wrap__`,
:func:`__array_prepare__`, :data:`__array_priority__` mechanism
described below (which may eventually be deprecated).
described below for ufuncs (which may eventually be deprecated).

.. py:method:: class.__array_finalize__(obj)

Expand Down
42 changes: 42 additions & 0 deletions numpy/core/src/multiarray/methods.c
Original file line number Diff line number Diff line change
Expand Up @@ -1007,6 +1007,45 @@ array_getarray(PyArrayObject *self, PyObject *args)
}


static PyObject *
array_ufunc(PyArrayObject *self, PyObject *args, PyObject *kwds)
{
PyObject *ufunc, *method_name, *normal_args, *ufunc_method, *result;

if (PyTuple_Size(args) < 2) {
PyErr_SetString(PyExc_TypeError,
"__array_ufunc__ requires at least 2 arguments");
return NULL;
}
ufunc = PyTuple_GET_ITEM(args, 0);
if (ufunc == NULL) {
return NULL;
}

method_name = PyTuple_GET_ITEM(args, 1);
if (method_name == NULL) {
return NULL;
}

normal_args = PyTuple_GetSlice(args, 2, PyTuple_GET_SIZE(args));
if (normal_args == NULL) {
return NULL;
}

ufunc_method = PyObject_GetAttr(ufunc, method_name);
if (ufunc_method == NULL) {
Py_DECREF(normal_args);
return NULL;
}

result = PyObject_Call(ufunc_method, normal_args, kwds);

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, why doesn't this loop? My understanding is that ufuncs cannot be used by ndarray subclasses using __array_override__ unless they clean themselve up, i.e., do not pass themselves to the call again so as to avoid looping. What am I missing?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're not missing anything: the subclass has to clean the arguments up before calling super. It really just replaces getattr(ufunc, method). Indeed, the main advantage over it is for a class like

class MaskedQuantity(MaskedArray, Quantity):
    def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
        ...
        result = super().__array_ufunc__(ufunc, method, *handled_inputs, **handled_kwargs)
        ...
        return handled_result

For this class, super passes on to MaskedArray, and MaskedArray's super will not go to ndarray as it normally would, but to Quantity.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

p.s. The looping was of course why I needed to be sure that the ndarray.__array_ufunc__ method is not seen as an override...

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since the base function is never called by the ufunc, why not just give it another name, say __array_ufunc_base__ or some such. Subclasses can then call it if they want.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@charris - renaming it would beat the whole point of using super --the subclass cannot really know which class is above it! See the example above: MaskedArray cannot know whether its super will go to ndarray or to Quantity, and by insisting that the names are the same it doesn't have to check.

(but I agree that it is a bit strange that the base __array_ufunc__ is not simply part of the ufunc machinery -- with its arguments already normalized at the very least it could enter the chain later. But that is for a later PR... For now, I'll just add a TODO)

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Multiple inheritance would also be a hassle, as it already is...

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, I'm missing some context here to understand the question – can you elaborate?

@charris charris Mar 29, 2017 •

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The idea here is to add __array_ufunc__ to ndarray. That base implementation then calls the relevant ufunc, which in turn, would normally call __array_ufunc__ again. To avoid that endless loop, PyUFunc_CheckOverride is modified so that it does not make the call when __array_ufunc__ is the version defined in the ndarray base class.

@mhvk wants the function in the base class so he can call it from subclasses in his units implementation.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@charris - ndarray.__array_ufunc__ never gets called by the ufunc directly, only by a subclass that does result = super(subclass, self).__array_ufunc__(*inputs, **kwargs). In this use, it simply replaces the getattr(ufunc, method)(*inputs, **kwargs) that was initially recommended (indeed, as is, it just does that; this can be sped up later). The main advantage of all this is that by making super possible, we allow multiple inheritance using the standard python method

@njsmith - for context, maybe most useful to look at the updated docs, in particular https://github.com/charris/numpy/pull/5/files#diff-5a79b101110fd040a0cd5a254b4742f6R515 (if that isn't clear, let me know -- it is supposed to explain why we do things this way!).

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, I see we both answered. Note that this is not specific to Quantity -- it just follows standard python practice.

Py_DECREF(normal_args);
Py_DECREF(ufunc_method);
/* no need to DECREF borrowed references ufunc and method_name */
return result;
}


static PyObject *
array_copy(PyArrayObject *self, PyObject *args, PyObject *kwds)
{
Expand Down Expand Up @@ -2429,6 +2468,9 @@ NPY_NO_EXPORT PyMethodDef array_methods[] = {
{"__array_wrap__",
(PyCFunction)array_wraparray,
METH_VARARGS, NULL},
{"__array_ufunc__",
(PyCFunction)array_ufunc,
METH_VARARGS | METH_KEYWORDS, NULL},

/* for the sys module */
{"__sizeof__",
Expand Down
55 changes: 50 additions & 5 deletions numpy/core/src/private/ufunc_override.c
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
#include "npy_pycompat.h"
#include "numpy/ufuncobject.h"
#include "get_attr_string.h"
#include "npy_import.h"

#include "ufunc_override.h"

Expand Down Expand Up @@ -169,6 +170,47 @@ normalize_at_args(PyUFuncObject *ufunc, PyObject *args,
return;
}

/*
* Check whether an object has __array_ufunc__ defined on its class and it
* is not the default, i.e., the object is not an ndarray, and its
* __array_ufunc__ is not the same as that of ndarray.
*
* Note that since this module is used with both multiarray and umath, we do
* not have access to PyArray_Type and therewith neither to PyArray_CheckExact
* nor to the default __array_ufunc__ method, so instead we import locally.
* TODO: Can this really not be done more smartly?
*/
static int
has_non_default_array_ufunc(PyObject *obj)

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about something like is_ndarray_array_ufunc?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It checks two things: whether the class has __array_ufunc__ and, if so, whether it is different from that of ndarray...

{
static PyObject *ndarray = NULL;
static PyObject *ndarray_array_ufunc = NULL;
PyTypeObject *cls_array_ufunc;
int non_default;

/* on first entry, import and cache ndarray and its __array_ufunc__ */
if (ndarray == NULL) {
npy_cache_import("numpy.core.multiarray", "ndarray", &ndarray);
ndarray_array_ufunc = PyObject_GetAttrString(ndarray,
"__array_ufunc__");
}

/* Fast return for ndarray */
if (Py_TYPE(obj) == ndarray) {
return 0;
}
/* does the class define __array_ufunc__? */
cls_array_ufunc = PyArray_GetAttrString_SuppressException(
Py_TYPE(obj), "__array_ufunc__");
if (cls_array_ufunc == NULL) {
return 0;
}
/* is it different from ndarray.__array_ufunc__? */
non_default = (cls_array_ufunc != ndarray_array_ufunc);
Py_DECREF(cls_array_ufunc);
return non_default;
}

/*
* Check a set of args for the `__array_ufunc__` method. If more than one of
* the input arguments implements `__array_ufunc__`, they are tried in the
Expand Down Expand Up @@ -250,11 +292,14 @@ PyUFunc_CheckOverride(PyUFuncObject *ufunc, char *method,
obj = out_kwd_obj;
}
}
tmp = PyArray_GetAttrString_SuppressException(obj, "__array_ufunc__");
if (tmp) {
Py_DECREF(tmp);
with_override[noa] = obj;
++noa;
/*
* Now see if the object provides an __array_ufunc__. However, we should
* ignore the base ndarray.__ufunc__, so we skip any ndarray as well as
* any ndarray subclass instances that did not override __array_ufunc__.
*/
if (has_non_default_array_ufunc(obj)) {
with_override[noa] = obj;
++noa;
}
}

Expand Down
9 changes: 6 additions & 3 deletions numpy/core/tests/test_multiarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -2907,7 +2907,8 @@ def norm(result):
"__array_ufunc__")
else:
if (isinstance(obj, np.ndarray) and
not hasattr(obj, "__array_ufunc__")):
(type(obj).__array_ufunc__ is
np.ndarray.__array_ufunc__)):
# __array__ gets ignored
res = norm(arr_method(obj))
assert_(res.__class__ is obj.__class__)
Expand All @@ -2923,7 +2924,8 @@ def norm(result):
assert_equal(res[1], ufunc)
else:
if (isinstance(obj, np.ndarray) and
not hasattr(obj, "__array_ufunc__")):
(type(obj).__array_ufunc__ is
np.ndarray.__array_ufunc__)):
# __array__ gets ignored
res = norm(arr_rmethod(obj))
assert_(res.__class__ is obj.__class__)
Expand All @@ -2944,7 +2946,8 @@ def norm(result):
assert_(res[-1]["out"][0] is arr)
else:
if (isinstance(obj, np.ndarray) and
not hasattr(obj, "__array_ufunc__")):
(type(obj).__array_ufunc__ is
np.ndarray.__array_ufunc__)):
# __array__ gets ignored
assert_(arr_imethod(obj) is arr)
else:
Expand Down
80 changes: 80 additions & 0 deletions numpy/core/tests/test_umath.py
Original file line number Diff line number Diff line change
Expand Up @@ -1815,6 +1815,86 @@ def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
assert_equal(res[3], (1, 1))
assert_equal(res[4], {'out': (a,)})

def test_ufunc_override_with_super(self):

class A(np.ndarray):
def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
args = []
in_no = []
for i, input_ in enumerate(inputs):
if isinstance(input_, A):
in_no.append(i)
args.append(input_.view(np.ndarray))
else:
args.append(input_)

outputs = kwargs.pop('out', [])
out_no = []
if outputs:
out_args = []
for j, output in enumerate(outputs):
if isinstance(output, A):
out_no.append(j)
out_args.append(output.view(np.ndarray))
else:
out_args.append(output)
kwargs['out'] = tuple(out_args)

info = {key: no for (key, no) in (('inputs', in_no),
('outputs', out_no))
if no != []}

results = super(A, self).__array_ufunc__(ufunc, method,
*args, **kwargs)
if not isinstance(results, tuple):
if not isinstance(results, np.ndarray):
return results
results = (results,)

if outputs == []:
outputs = [None] * len(results)
results = tuple(result.view(A) if output is None else output
for result, output in zip(results, outputs))
if isinstance(results[0], A):
results[0].info = info

return results[0] if len(results) == 1 else results

d = np.arange(5.)
a = np.arange(5.).view(A)
# 1 input, 1 output
b = np.sin(a)
check = np.sin(d)
assert_(np.all(check == b))
assert_equal(b.info, {'inputs': [0]})
b = np.sin(d, out=(a,))
assert_(np.all(check == b))
assert_equal(b.info, {'outputs': [0]})
assert_(b is a)
a = np.arange(5.).view(A)
b = np.sin(a, out=a)
assert_(np.all(check == b))
assert_equal(b.info, {'inputs': [0], 'outputs': [0]})
# 1 input, 2 outputs
a = np.arange(5.).view(A)
b1, b2 = np.modf(a)
assert_equal(b1.info, {'inputs': [0]})
b1, b2 = np.modf(d, out=(None, a))
assert_(b2 is a)
assert_equal(b1.info, {'outputs': [1]})
a = np.arange(5.).view(A)
b = np.arange(5.).view(A)
c1, c2 = np.modf(a, out=(a, b))
assert_(c1 is a)
assert_(c2 is b)
assert_equal(c1.info, {'inputs': [0], 'outputs': [0, 1]})
# 2 input, 1 output
a = np.arange(5.).view(A)
b = np.arange(5.).view(A)
c = np.add(a, b, out=a)
assert_(c is a)
assert_equal(c.info, {'inputs': [0, 1], 'outputs': [0]})


class TestChoose(TestCase):
def test_mixed(self):
Expand Down
Loading