Skip to content

BUG: __matmul__ should return NotImplemented instead of raising a TypeError #188

@lucascolley

Description

@lucascolley

__matmul__ doesn't work with fallback to reflected operators per https://docs.python.org/3/library/constants.html#NotImplemented

In [1]: import scipy, numpy as np, array_api_strict as xp

In [3]: class HelloOp(scipy.sparse.linalg.LinearOperator):
   ...:     def _matvec(self, x):
   ...:         return x
   ...:
   ...:     def __rmatmul__(self, other):
   ...:         print("hello :)")
   ...:

In [4]: H = HelloOp(dtype=None, shape=(2, 2))

In [5]: np.eye(2) @ H
hello :)

In [6]: xp.eye(2) @ H
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[6], line 1
----> 1 xp.eye(2) @ H

File ~/ghq/github.com/scipy/scipy/.pixi/envs/array-api-cpu/lib/python3.13/site-packages/array_api_strict/_array_object.py:832, in Array.__matmul__(self, other)
    828 def __matmul__(self, other: Array, /) -> Array:
    829     """
    830     Performs the operation __matmul__.
    831     """
--> 832     self._check_type_device(other)
    833     # matmul is not defined for scalars, but without this, we may get
    834     # the wrong error message from asarray.
    835     other = self._check_allowed_dtypes(other, "numeric", "__matmul__")

File ~/ghq/github.com/scipy/scipy/.pixi/envs/array-api-cpu/lib/python3.13/site-packages/array_api_strict/_array_object.py:241, in Array._check_type_device(self, other)
    239 # Disallow subclasses of Python scalars, such as np.float64 and np.complex128
    240 elif type(other) not in (bool, int, float, complex):
--> 241     raise TypeError(f"Expected Array or Python scalar; got {type(other)}")

TypeError: Expected Array or Python scalar; got <class '__main__.HelloOp'>

@ev-br happy to accept a patch for this?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions