diff --git a/array_api_strict/_creation_functions.py b/array_api_strict/_creation_functions.py index b34af5a..63bc9c4 100644 --- a/array_api_strict/_creation_functions.py +++ b/array_api_strict/_creation_functions.py @@ -107,8 +107,12 @@ def asarray( res = np.array(obj, dtype=_np_dtype, copy=copy) - # numpy default dtype may differ; if so, adjust the dtype - if dtype is None and device is not None: + # numpy default dtype may differ; if so, adjust the dtype--- + # unless `obj` is already an array, potentially from some other library. + # In the latter case, `obj.dtype` is a thing, numpy has already done the + # conversion and `res.dtype` is the numpy analog of `obj.dtype` + # (if numpy failed to convert `obj`, it has already raised an exception). + if dtype is None and device is not None and not hasattr(obj, "dtype"): res_dtype = DType(res.dtype) # The dtype selected by Numpy might not be the default dtype # on this device. We thus find the default dtype for the dtype "kind", and diff --git a/array_api_strict/tests/test_creation_functions.py b/array_api_strict/tests/test_creation_functions.py index 7031120..06c5d87 100644 --- a/array_api_strict/tests/test_creation_functions.py +++ b/array_api_strict/tests/test_creation_functions.py @@ -368,6 +368,13 @@ def test_asarray_device_2(): assert y.dtype == float64 +def test_asarray_device_1(): + # regression test for https://github.com/data-apis/array-api-strict/issues/222 + x = np.ones(3, dtype=np.float32) + y = asarray(x, device=Device('device1')) + assert y.dtype == float32 + + @pytest.mark.parametrize("api_version", ['2021.12', '2022.12', '2023.12']) def from_dlpack_2023_12(api_version): if api_version != '2022.12':