Description
Background
Ordinary NumPy arrays have a peculiar operator behaviour:
- if an operator like
__add__
fails, then instead of returningNotImplemented
(which would be idiomatic Python), - NumPy decomposes the array into basic Python types (such as
float
orint
), and then calls the corresponding reverse operator (like__radd__
) on these elements and the RHS - It then collates the results into a new array.
It is too late for NumPy to change this since this would break a lot code.
Motivation
Consider someone implementing a class that must interact with arrays. For example, a rectangle class defined by storing the opposite corners of a rectangle. If x = Rectange(...)
and a
is an array, we want to support both x + a
and a + x
. If the decomposition/collation described above happens, then this will not work: a + x
will try to build an array of rectangles offset by floats.
Proposal
Conformant implementations of the Array API should return NotImplemented
when they don't know how to evaluate an operator with their arrays—rather than this behavior being implementation-defined. Also, it would be useful to have a test in the conformance test suite that verifies this.