Skip to content

Commit 6f02ec3

Browse files
Merge pull request #1964 from IntelPython/usm_ndrray-array-protocol-must-raise
Usm ndrray array protocol must raise
2 parents 0ac353f + 8393a75 commit 6f02ec3

File tree

3 files changed

+25
-0
lines changed

3 files changed

+25
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
2121
* Improved performance of `tensor.cumulative_sum`, `tensor.cumulative_prod`, `tensor.cumulative_logsumexp` as well as performance of boolean indexing [gh-1923](https://github.com/IntelPython/dpctl/pull/1923)
2222
* Improved performance of `tensor.min`, `tensor.max`, `tensor.logsumexp`, `tensor.reduce_hypot` for floating point type arrays by at least 2x [gh-1932](https://github.com/IntelPython/dpctl/pull/1932)
2323
* Extended `tensor.asarray` to support objects that implement `__usm_ndarray__` property to be interpreted as `usm_ndarray` objects [gh-1959](https://github.com/IntelPython/dpctl/pull/1959)
24+
* `dpctl.tensor.usm_ndarray` object disallows implicit conversions to NumPy array [gh-1964](https://github.com/IntelPython/dpctl/pull/1964)
2425

2526
### Fixed
2627

dpctl/tensor/_usmarray.pyx

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1552,6 +1552,21 @@ cdef class usm_ndarray:
15521552
def __repr__(self):
15531553
return usm_ndarray_repr(self)
15541554

1555+
def __array__(self, dtype=None, /, *, copy=None):
1556+
"""NumPy's array protocol method to disallow implicit conversion.
1557+
1558+
Without this definition, `numpy.asarray(usm_ar)` converts
1559+
usm_ndarray instance into NumPy array with data type `object`
1560+
and every element being 0d usm_ndarray.
1561+
1562+
https://github.com/IntelPython/dpctl/pull/1384#issuecomment-1707212972
1563+
"""
1564+
raise TypeError(
1565+
"Implicit conversion to a NumPy array is not allowed. "
1566+
"Use `dpctl.tensor.asnumpy` to copy data from this "
1567+
"`dpctl.tensor.usm_ndarray` instance to NumPy array"
1568+
)
1569+
15551570

15561571
cdef usm_ndarray _real_view(usm_ndarray ary):
15571572
"""

dpctl/tests/test_usm_ndarray_ctor.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2659,3 +2659,12 @@ def test_setitem_copy_as_contig_alignment(dt):
26592659
x[1:, ...] = vals
26602660
assert dpt.all(x[0] == 0)
26612661
assert dpt.all(x[1:, :] == vals)
2662+
2663+
2664+
def test_asarray_property():
2665+
get_queue_or_skip()
2666+
2667+
x = dpt.ones(11, dtype="i4")
2668+
2669+
with pytest.raises(TypeError):
2670+
np.asarray(x)

0 commit comments

Comments
 (0)