Skip to content

API: Introduce copy argument for np.asarray [Array API] #25168

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Feb 29, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Add keyword argument to
  • Loading branch information
mtsokol committed Feb 29, 2024
commit 8f5d130f8d44b9f9a0effe4ba727c5920622071d
14 changes: 9 additions & 5 deletions numpy/_core/_add_newdocs.py
Original file line number Diff line number Diff line change
Expand Up @@ -2943,11 +2943,15 @@

add_newdoc('numpy._core.multiarray', 'ndarray', ('__array__',
"""
a.__array__([dtype], /)

Returns either a new reference to self if dtype is not given or a new array
of provided data type if dtype is different from the current dtype of the
array.
a.__array__([dtype], /, *, copy=None)

For ``dtype`` parameter it returns either a new reference to self if
``dtype`` is not given or a new array of provided data type if ``dtype``
is different from the current data type of the array.
For ``copy`` parameter it returns a new reference to self if
``copy=False`` or ``copy=None`` and copying isn't enforced by ``dtype``
parameter. The method returns a new array for ``copy=True``, regardless of
``dtype`` parameter.

"""))

Expand Down
32 changes: 24 additions & 8 deletions numpy/_core/src/multiarray/methods.c
Original file line number Diff line number Diff line change
Expand Up @@ -924,13 +924,16 @@ array_wraparray(PyArrayObject *self, PyObject *args)


static PyObject *
array_getarray(PyArrayObject *self, PyObject *args)
array_getarray(PyArrayObject *self, PyObject *args, PyObject *kwds)
{
PyArray_Descr *newtype = NULL;
NPY_COPYMODE copy = NPY_COPY_IF_NEEDED;
static char *kwlist[] = {"", "copy", NULL};
PyObject *ret;

if (!PyArg_ParseTuple(args, "|O&:__array__",
PyArray_DescrConverter, &newtype)) {
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&$O&:__array__", kwlist,
PyArray_DescrConverter, &newtype,
PyArray_CopyConverter, &copy)) {
Py_XDECREF(newtype);
return NULL;
}
Expand Down Expand Up @@ -960,13 +963,26 @@ array_getarray(PyArrayObject *self, PyObject *args)
Py_INCREF(self);
}

if ((newtype == NULL) || PyArray_EquivTypes(PyArray_DESCR(self), newtype)) {
return (PyObject *)self;
}
else {
if (copy == NPY_COPY_ALWAYS) {
if (newtype == NULL) {
newtype = PyArray_DESCR(self);
}
ret = PyArray_CastToType(self, newtype, 0);
Py_DECREF(self);
return ret;
} else { // copy == NPY_COPY_IF_NEEDED || copy == NPY_COPY_NEVER
if (newtype == NULL || PyArray_EquivTypes(PyArray_DESCR(self), newtype)) {
return (PyObject *)self;
}
if (copy == NPY_COPY_IF_NEEDED) {
ret = PyArray_CastToType(self, newtype, 0);
Py_DECREF(self);
return ret;
} else { // copy == NPY_COPY_NEVER
PyErr_SetString(PyExc_ValueError,
"Unable to avoid copy while creating an array from given array.");
return NULL;
}
}
}

Expand Down Expand Up @@ -2848,7 +2864,7 @@ NPY_NO_EXPORT PyMethodDef array_methods[] = {
/* for subtypes */
{"__array__",
(PyCFunction)array_getarray,
METH_VARARGS, NULL},
METH_VARARGS | METH_KEYWORDS, NULL},
{"__array_finalize__",
(PyCFunction)array_finalizearray,
METH_O, NULL},
Expand Down
13 changes: 13 additions & 0 deletions numpy/_core/tests/test_multiarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -8456,6 +8456,19 @@ def __array__(self):
with pytest.raises(ValueError):
np.array(arr, copy=copy)

def test___array__copy_arg(self):
a = np.ones((10, 10), dtype=int)

assert np.shares_memory(a, a.__array__())
assert not np.shares_memory(a, a.__array__(float))
assert not np.shares_memory(a, a.__array__(float, copy=None))
assert not np.shares_memory(a, a.__array__(copy=True))
assert np.shares_memory(a, a.__array__(copy=None))
assert np.shares_memory(a, a.__array__(copy=False))
assert np.shares_memory(a, a.__array__(int, copy=False))
with pytest.raises(ValueError):
np.shares_memory(a, a.__array__(float, copy=False))

@pytest.mark.parametrize(
"arr", [np.ones(()), np.arange(81).reshape((9, 9))])
@pytest.mark.parametrize("order1", ["C", "F", None])
Expand Down
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy