Skip to content

Commit a3c04ab

Browse files
committed
ENH: rm __array__, add __buffer__
1 parent e4b6bfe commit a3c04ab

File tree

1 file changed

+11
-23
lines changed

1 file changed

+11
-23
lines changed

array_api_strict/_array_object.py

+11-23
Original file line numberDiff line numberDiff line change
@@ -66,9 +66,6 @@ def __hash__(self):
6666

6767
_default = object()
6868

69-
# See https://github.com/data-apis/array-api-strict/issues/67 and the comment
70-
# on __array__ below.
71-
_allow_array = True
7269

7370
class Array:
7471
"""
@@ -161,26 +158,17 @@ def __repr__(self: Array, /) -> str:
161158
# This was implemented historically for compatibility, and removing it has
162159
# caused issues for some libraries (see
163160
# https://github.com/data-apis/array-api-strict/issues/67).
164-
def __array__(self, dtype: None | np.dtype[Any] = None, copy: None | bool = None) -> npt.NDArray[Any]:
165-
# We have to allow this to be internally enabled as there's no other
166-
# easy way to parse a list of Array objects in asarray().
167-
if _allow_array:
168-
if self._device != CPU_DEVICE:
169-
raise RuntimeError(f"Can not convert array on the '{self._device}' device to a Numpy array.")
170-
# copy keyword is new in 2.0.0; for older versions don't use it
171-
# retry without that keyword.
172-
if np.__version__[0] < '2':
173-
return np.asarray(self._array, dtype=dtype)
174-
elif np.__version__.startswith('2.0.0-dev0'):
175-
# Handle dev version for which we can't know based on version
176-
# number whether or not the copy keyword is supported.
177-
try:
178-
return np.asarray(self._array, dtype=dtype, copy=copy)
179-
except TypeError:
180-
return np.asarray(self._array, dtype=dtype)
181-
else:
182-
return np.asarray(self._array, dtype=dtype, copy=copy)
183-
raise ValueError("Conversion from an array_api_strict array to a NumPy ndarray is not supported")
161+
162+
# Instead of `__array__` we now implement the buffer protocol.
163+
# Note that it makes array-apis-strict requiring python>=3.12
164+
def __buffer__(self, flags):
165+
print('__buffer__')
166+
if self._device != CPU_DEVICE:
167+
raise RuntimeError(f"Can not convert array on the '{self._device}' device to a Numpy array.")
168+
return memoryview(self._array)
169+
def __release_buffer(self, buffer):
170+
print('__release__')
171+
# XXX anything to do here?
184172

185173
# These are various helper functions to make the array behavior match the
186174
# spec in places where it either deviates from or is more strict than

0 commit comments

Comments
 (0)