Array API compatible wrapper for :py:func:`np.asarray `. See its docstring for more information.
(
obj: Union[
Array,
bool,
int,
float,
NestedSequence[bool | int | float],
SupportsBufferProtocol,
],
/,
*,
dtype: Optional[Dtype] = None,
device: Optional[Device] = None,
copy: Optional[Union[bool, np._CopyMode]] = None,
)
| 29 | |
| 30 | |
| 31 | def asarray( |
| 32 | obj: Union[ |
| 33 | Array, |
| 34 | bool, |
| 35 | int, |
| 36 | float, |
| 37 | NestedSequence[bool | int | float], |
| 38 | SupportsBufferProtocol, |
| 39 | ], |
| 40 | /, |
| 41 | *, |
| 42 | dtype: Optional[Dtype] = None, |
| 43 | device: Optional[Device] = None, |
| 44 | copy: Optional[Union[bool, np._CopyMode]] = None, |
| 45 | ) -> Array: |
| 46 | """ |
| 47 | Array API compatible wrapper for :py:func:`np.asarray <numpy.asarray>`. |
| 48 | |
| 49 | See its docstring for more information. |
| 50 | """ |
| 51 | # _array_object imports in this file are inside the functions to avoid |
| 52 | # circular imports |
| 53 | from ._array_object import Array |
| 54 | |
| 55 | _check_valid_dtype(dtype) |
| 56 | if device not in ["cpu", None]: |
| 57 | raise ValueError(f"Unsupported device {device!r}") |
| 58 | if copy in (False, np._CopyMode.IF_NEEDED): |
| 59 | # Note: copy=False is not yet implemented in np.asarray |
| 60 | raise NotImplementedError("copy=False is not yet implemented") |
| 61 | if isinstance(obj, Array): |
| 62 | if dtype is not None and obj.dtype != dtype: |
| 63 | copy = True |
| 64 | if copy in (True, np._CopyMode.ALWAYS): |
| 65 | return Array._new(np.array(obj._array, copy=True, dtype=dtype)) |
| 66 | return obj |
| 67 | if dtype is None and isinstance(obj, int) and (obj > 2 ** 64 or obj < -(2 ** 63)): |
| 68 | # Give a better error message in this case. NumPy would convert this |
| 69 | # to an object array. TODO: This won't handle large integers in lists. |
| 70 | raise OverflowError("Integer out of bounds for array dtypes") |
| 71 | res = np.asarray(obj, dtype=dtype) |
| 72 | return Array._new(res) |
| 73 | |
| 74 | |
| 75 | def arange( |