Skip to content

Commit 3abfdbd

Browse files
committed
fix: delegate no-copy reshape to namespace
1 parent bbfe8c2 commit 3abfdbd

2 files changed

Lines changed: 23 additions & 0 deletions

File tree

src/array_api_compat/common/_aliases.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -444,6 +444,10 @@ def permute_dims(x: Array, /, axes: tuple[int, ...], xp: Namespace) -> Array:
444444
return xp.transpose(x, axes)
445445

446446

447+
def _reshape_supports_copy(xp: Namespace) -> bool:
448+
return "copy" in inspect.signature(xp.reshape).parameters
449+
450+
447451
# np.reshape calls the keyword argument 'newshape' instead of 'shape'
448452
def reshape(
449453
x: Array,
@@ -457,6 +461,8 @@ def reshape(
457461
if copy is True:
458462
x = x.copy()
459463
elif copy is False:
464+
if _reshape_supports_copy(xp):
465+
return xp.reshape(x, shape, copy=False, **kwargs)
460466
y = x.view()
461467
y.shape = shape
462468
return y

tests/test_common.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import math
2+
import warnings
23

34
import pytest
45
import numpy as np
@@ -17,6 +18,7 @@
1718
from array_api_compat import (
1819
device, is_array_api_obj, is_lazy_array, is_writeable_array, size, to_device
1920
)
21+
from array_api_compat.common._aliases import reshape
2022
from array_api_compat.common._helpers import _DASK_DEVICE
2123
from ._helpers import all_libraries, import_, wrapped_libraries, xfail
2224

@@ -376,3 +378,18 @@ def test_clip_out(library):
376378
xp.clip(x, 15, 25, out=out)
377379
expect = xp.asarray([15, 20, 25])
378380
assert xp.all(out == expect)
381+
382+
383+
def test_reshape_copy_false_returns_a_view_without_deprecation():
384+
x = np.arange(12)
385+
with warnings.catch_warnings():
386+
warnings.simplefilter("error", DeprecationWarning)
387+
y = reshape(x, (3, 4), xp=np, copy=False)
388+
389+
assert y.shape == (3, 4)
390+
assert np.shares_memory(x, y)
391+
392+
393+
def test_reshape_copy_false_rejects_an_input_that_needs_a_copy():
394+
with pytest.raises((ValueError, AttributeError)):
395+
reshape(np.arange(12).reshape(3, 4).T, (2, 6), xp=np, copy=False)

0 commit comments

Comments
 (0)