Thanks to visit codestin.com
Credit goes to github.com

Skip to content

ENH: Add __array__ to the array_api Array object #20527

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Dec 7, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions numpy/array_api/_array_object.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@

if TYPE_CHECKING:
from ._typing import Any, PyCapsule, Device, Dtype
import numpy.typing as npt

import numpy as np

Expand Down Expand Up @@ -108,6 +109,17 @@ def __repr__(self: Array, /) -> str:
mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix)
return prefix + mid + suffix

# This function is not required by the spec, but we implement it here for
# convenience so that np.asarray(np.array_api.Array) will work.
def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]:
"""
Warning: this method is NOT part of the array API spec. Implementers
of other libraries need not include it, and users should not assume it
will be present in other implementations.

"""
return np.asarray(self._array, dtype=dtype)

# These are various helper functions to make the array behavior match the
# spec in places where it either deviates from or is more strict than
# NumPy behavior
Expand Down
7 changes: 7 additions & 0 deletions numpy/array_api/tests/test_array_object.py
Original file line number Diff line number Diff line change
Expand Up @@ -315,3 +315,10 @@ def test_array_properties():
assert a.mT.shape == (1, 3, 2)
assert isinstance(b.mT, Array)
assert b.mT.shape == (3, 2)

def test___array__():
a = ones((2, 3), dtype=int16)
assert np.asarray(a) is a._array
b = np.asarray(a, dtype=np.float64)
assert np.all(np.equal(b, np.ones((2, 3), dtype=np.float64)))
assert b.dtype == np.float64