Skip to content

Can we promise to delegate to reverse operators ? #732

Closed
@NeilGirdhar

Description

@NeilGirdhar

Background

Ordinary NumPy arrays have a peculiar operator behaviour:

  • if an operator like __add__ fails, then instead of returning NotImplemented (which would be idiomatic Python),
  • NumPy decomposes the array into basic Python types (such as float or int), 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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions