Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 15 additions & 3 deletions python/src/ops.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1765,23 +1765,35 @@ void init_ops(nb::module_& m) {
)pbdoc");
m.def(
"asarray",
[](const nb::object& a, std::optional<mx::Dtype> dtype) {
[](const nb::object& a,
std::optional<mx::Dtype> dtype,
std::optional<bool> copy) {
if (copy.has_value() && !*copy) {
throw std::invalid_argument("[asarray] copy=False is not supported.");
}
return create_array(a, dtype);
},
nb::arg(),
"dtype"_a = nb::none(),
nb::kw_only(),
"copy"_a = nb::none(),
nb::sig(
"def asarray(a: Union[scalar, array, Sequence], dtype: "
"Optional[Dtype] = None) -> array"),
"def asarray(a: Union[scalar, array, Sequence], dtype: Optional[Dtype] = None, *, copy: Optional[bool] = None) -> array"),
R"pbdoc(
Convert the input to an array.

Args:
a: Input data.
dtype (Dtype, optional): The desired data-type for the array.
copy (bool, optional): Must be ``True`` or unspecified. ``False``
is not supported, since MLX has no in-place operations and
cannot return a non-copying view.

Returns:
array: An array interpretation of the input.

Raises:
ValueError: If ``copy`` is ``False``.
)pbdoc");
m.def(
"zeros_like",
Expand Down
11 changes: 11 additions & 0 deletions python/tests/test_array.py
Original file line number Diff line number Diff line change
Expand Up @@ -2152,6 +2152,17 @@ def test_array_namespace_asarray(self):
arr_pass = xp.asarray(existing)
self.assertEqual(arr_pass.tolist(), [4, 5, 6])

def test_asarray_copy(self):
existing = mx.array([1, 2, 3])

self.assertEqual(mx.asarray(existing, copy=True).tolist(), [1, 2, 3])
self.assertEqual(
mx.asarray(existing, dtype=mx.float32, copy=True).dtype, mx.float32
)

with self.assertRaises(ValueError):
mx.asarray(existing, copy=False)

def test_asarray(self):
# List inputs
self.assertEqual(mx.asarray([1, 2, 3]).tolist(), [1, 2, 3])
Expand Down
Loading