Skip to content

Commit f34fa52

Browse files
authored
Merge pull request #72 from betatim/asarray-default-device
FIX Propagate input array's device in `asarray`
2 parents b625bbe + 349c4ff commit f34fa52

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

array_api_strict/_creation_functions.py

+6
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,8 @@ def asarray(
6767
if dtype is not None:
6868
_np_dtype = dtype._np_dtype
6969
_check_device(device)
70+
if isinstance(obj, Array) and device is None:
71+
device = obj.device
7072

7173
if np.__version__[0] < '2':
7274
if copy is False:
@@ -158,6 +160,8 @@ def empty_like(
158160

159161
_check_valid_dtype(dtype)
160162
_check_device(device)
163+
if device is None:
164+
device = x.device
161165

162166
if dtype is not None:
163167
dtype = dtype._np_dtype
@@ -260,6 +264,8 @@ def full_like(
260264

261265
_check_valid_dtype(dtype)
262266
_check_device(device)
267+
if device is None:
268+
device = x.device
263269

264270
if dtype is not None:
265271
dtype = dtype._np_dtype

array_api_strict/tests/test_creation_functions.py

+12-1
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
zeros_like,
2424
)
2525
from .._dtypes import float32, float64
26-
from .._array_object import Array, CPU_DEVICE
26+
from .._array_object import Array, CPU_DEVICE, Device
2727
from .._flags import set_array_api_strict_flags
2828

2929
def test_asarray_errors():
@@ -97,6 +97,17 @@ def test_asarray_copy():
9797
a[0] = 0
9898
assert all(b[0] == 0)
9999

100+
101+
def test_asarray_device_inference():
102+
assert asarray([1, 2, 3]).device == CPU_DEVICE
103+
104+
x = asarray([1, 2, 3])
105+
assert asarray(x).device == CPU_DEVICE
106+
107+
device1 = Device("device1")
108+
x = asarray([1, 2, 3], device=device1)
109+
assert asarray(x).device == device1
110+
100111
def test_arange_errors():
101112
arange(1, device=CPU_DEVICE) # Doesn't error
102113
assert_raises(ValueError, lambda: arange(1, device="cpu"))

0 commit comments

Comments
 (0)