Skip to content

BUG: np.ma.asarray does not interrogate a foreign object for __array__. Should it? #29475

@ikrommyd

Description

@ikrommyd

Describe the issue:

This is how the masked and not-masked asarray treats a numpy array

In [1]: import numpy as np

In [2]: array = np.ma.array([1,2,3], mask=[False,True,False])

In [3]: np.asarray(array)
Out[3]: array([1, 2, 3])

In [4]: np.ma.asarray(array)
Out[4]:
masked_array(data=[1, --, 3],
             mask=[False,  True, False],
       fill_value=999999)

Now if I wrap my array object into a custom array class that implements __array__. np.asarray is fine with it but np.ma.asarray gives RecursionError: maximum recursion depth exceeded when you try to look at the array.

In [5]: class Array:
   ...:     def __init__(self, data):
   ...:         self._data = data
   ...:     def __array__(self):
   ...:         return self._data
   ...:

In [6]: x = Array(array)

In [7]: np.asarray(x)
Out[7]: array([1, 2, 3])

In [8]: np.ma.asarray(x)
Out[8]: ---------------------------------------------------------------------------
RecursionError                            Traceback (most recent call last)

It appears that looking at the data is problematic

In [9]: out = np.ma.asarray(x)

In [10]: out.mask
Out[10]: array([False,  True, False])

In [11]: out.data
Out[11]: ---------------------------------------------------------------------------
RecursionError                            Traceback (most recent call last)

Now of course, if I use the __array__ method manually, np.ma.asarray is fine.

In [12]: np.ma.asarray(x.__array__())
Out[12]:
masked_array(data=[1, --, 3],
             mask=[False,  True, False],
       fill_value=999999)

Therefore, my bug report/question is should np.ma.asarray look for a __array__ to convert the object properly?

Reproduce the code example:

import numpy as np
array = np.ma.array([1,2,3], mask=[False,True,False])
class Array:
    def __init__(self, data):
        self._data = data
    def __array__(self):
        return self._data
x = Array(array)
print(np.asarray(x))
print(np.ma.asarray(x))

Error message:

Traceback (most recent call last):
  File "<python-input-0>", line 10, in <module>
    print(np.ma.asarray(x))
    ~~~~~^^^^^^^^^^^^^^^^^^
  File "/Users/iason/software/numpy/build-install/usr/lib/python3.13/site-packages/numpy/ma/core.py", line 4089, in __str__
    return str(self._insert_masked_print())
  File "/Users/iason/software/numpy/build-install/usr/lib/python3.13/site-packages/numpy/ma/core.py", line 4089, in __str__
    return str(self._insert_masked_print())
  File "/Users/iason/software/numpy/build-install/usr/lib/python3.13/site-packages/numpy/ma/core.py", line 4089, in __str__
    return str(self._insert_masked_print())
  [Previous line repeated 161 more times]
  File "/Users/iason/software/numpy/build-install/usr/lib/python3.13/site-packages/numpy/ma/core.py", line 4068, in _insert_masked_print
    data = self._data
           ^^^^^^^^^^
  File "/Users/iason/software/numpy/build-install/usr/lib/python3.13/site-packages/numpy/ma/core.py", line 3787, in _get_data
    return ndarray.view(self, self._baseclass)
           ~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^
RecursionError: maximum recursion depth exceeded

Python and NumPy Versions:

2.4.0.dev0+git20250728.f41d553
3.13.5 (tags/v3.13.5:6cb20a219a8, Jul 27 2025, 04:35:36) [Clang 17.0.0 (clang-1700.0.13.5)]

Runtime Environment:

[{'numpy_version': '2.4.0.dev0+git20250728.f41d553',
'python': '3.13.5 (tags/v3.13.5:6cb20a219a8, Jul 27 2025, 04:35:36) [Clang '
'17.0.0 (clang-1700.0.13.5)]',
'uname': uname_result(system='Darwin', node='coffeabox', release='24.5.0', version='Darwin Kernel Version 24.5.0: Tue Apr 22 19:53:27 PDT 2025; root:xnu-11417.121.6~2/RELEASE_ARM64_T6041', machine='arm64')},
{'simd_extensions': {'baseline': [], 'found': [], 'not_found': []}}]

Context for the issue:

Interoperability with NumPy when a foreign object is like a masked array (or can be converted into one).

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions