[Numpy-discussion] NEP: Dispatch Mechanism for NumPy’s high level API

Marten van Kerkwijk m.h.vankerkwijk at gmail.com
Mon Jun 4 10:34:49 EDT 2018


Hi Stephan,

Another potential consideration in favor of NotImplementedButCoercible is
> for subclassing: we could use it to write the default implementations of
> ndarray.__array_ufunc__ and ndarray.__array_function__, e.g.,
>
> class ndarray:
>     def __array_ufunc__(self, *args, **kwargs):
>         return NotIImplementedButCoercible
>     def __array_function__(self, *args, **kwargs):
>         return NotIImplementedButCoercible
>
> I think (not 100% sure yet) this would result in exactly equivalent
> behavior to what ndarray.__array_ufunc__ currently does:
> http://www.numpy.org/neps/nep-0013-ufunc-overrides.html#
> subclass-hierarchies
>

As written would not work for ndarray subclasses, because the subclass will
generically change itself before calling super. At least for Quantity, say
if I add two quantities, the quantities will both be converted to arrays
(with one scaled so that the units match) and then the super call is done
with those modified arrays. This expects that the super call will actually
return a result (which it now can because all inputs are arrays).

But I think it would work to return `NotImplementedButCoercible` in the
case that perhaps you had in mind in the first place, in which any of the
*other* arguments had a `__array_ufunc__` implementation and `ndarray` thus
does not know what to do. For those cases, `ndarray` currently returns a
straight `NotImplemented`.

Though I am still a bit worried: this gets back to
`Quantity.__array_ufunc__`, but what does it do with it? It cannot just
pass it on, since then it is effectively telling, incorrectly, that the
*quantity* is coercible, which it is not. I guess at this point it would
have to change it to `NotImplemented`. Looking at my current
implementation, I see that if we made this change to
`ndarray.__array_ufunc__`, the implementation would mostly raise an
exception as it tried to view `NotImplementedButCoercible` as a quantity,
except for comparisons, where the output is not viewed at all (being
boolean and thus unit-less) and passed straight down. That said, we've said
the __array_ufunc__ implementation is experimental, so I think such small
annoyances are OK.

Overall, it is an intriguing idea, and I think it should be mentioned at
least in the NEP. It would be good, though, to have a few more examples of
how it would work in practice.

All the best,

Marten
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20180604/7d95d292/attachment-0001.html>


More information about the NumPy-Discussion mailing list