Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

API: Introducecopy argument fornp.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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
ngoldbaum merged 5 commits intonumpy:mainfrommtsokol:asarray-copy-arg
Feb 29, 2024
Merged
Show file tree
Hide file tree
Changes from1 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
PrevPrevious commit
NextNext commit
API: Update copy keyword across the codebase
  • Loading branch information
@mtsokol
mtsokol committedFeb 29, 2024
commit94dd1b5b15090334bf8f3ebc7399e7cb596241b0
18 changes: 10 additions & 8 deletionsnumpy/_core/_add_newdocs.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -807,12 +807,14 @@
a default ``dtype`` that can represent the values (by applying promotion
rules when necessary.)
copy : bool, optional
Iftrue (default), then the array data is copied.Otherwise, a copy
will only be made if ``__array__`` returns a copy, if obj is a nested
sequence, or if a copy is needed to satisfy any of the other
If``True`` (default), then the array data is copied.If ``None``,
a copywill only be made if ``__array__`` returns a copy, if obj is
a nestedsequence, or if a copy is needed to satisfy any of the other
requirements (``dtype``, ``order``, etc.). Note that any copy of
the data is shallow, i.e., for arrays with object dtype, the new
array will point to the same objects. See Examples for `ndarray.copy`.
For ``False`` it raises a ``ValueError`` if a copy cannot be avoided.
Default: ``True``.
order : {'K', 'A', 'C', 'F'}, optional
Specify the memory layout of the array. If object is not an array, the
newly created array will be in C order (row major) unless 'F' is
Expand All@@ -828,7 +830,7 @@
'F' F order F order
===== ========= ===================================================

When ``copy=False`` and a copy is made for other reasons, the result is
When ``copy=None`` and a copy is made for other reasons, the result is
the same as if ``copy=True``, with some exceptions for 'A', see the
Notes section. The default order is 'K'.
subok : bool, optional
Expand DownExpand Up@@ -915,7 +917,7 @@

add_newdoc('numpy._core.multiarray', 'asarray',
"""
asarray(a, dtype=None, order=None, *, device=None, like=None)
asarray(a, dtype=None, order=None, *, device=None,copy=None,like=None)

Convert the input to an array.

Expand All@@ -940,12 +942,12 @@

.. versionadded:: 2.0.0
copy : bool, optional
Iftrue, then the object is copied. Iffalse then the object is
If``True``, then the object is copied. If``None`` then the object is
copied only if needed, i.e. if ``__array__`` returns a copy, if obj
is a nested sequence, or if a copy is needed to satisfy any of
the other requirements (``dtype``, ``order``, etc.).
For ``np._CopyMode.NEVER`` it raises a ``ValueError`` if a copy
cannot be avoided.Default:false.
For ``False`` it raises a ``ValueError`` if a copy cannot be avoided.
Default:``None``.
${ARRAY_FUNCTION_LIKE}

.. versionadded:: 1.20.0
Expand Down
2 changes: 1 addition & 1 deletionnumpy/_core/_asarray.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -123,7 +123,7 @@ def require(a, dtype=None, requirements=None, *, like=None):
order = 'C'
requirements.remove('C')

arr = array(a, dtype=dtype, order=order, copy=False, subok=subok)
arr = array(a, dtype=dtype, order=order, copy=None, subok=subok)

for prop in requirements:
if not arr.flags[prop]:
Expand Down
6 changes: 3 additions & 3 deletionsnumpy/_core/function_base.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -300,14 +300,14 @@ def logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None,
"""
ndmax = np.broadcast(start, stop, base).ndim
start, stop, base = (
np.array(a, copy=False, subok=True, ndmin=ndmax)
np.array(a, copy=None, subok=True, ndmin=ndmax)
for a in (start, stop, base)
)
y = linspace(start, stop, num=num, endpoint=endpoint, axis=axis)
base = np.expand_dims(base, axis=axis)
if dtype is None:
return _nx.power(base, y)
return _nx.power(base, y).astype(dtype, copy=False)
return _nx.power(base, y).astype(dtype, copy=None)


def _geomspace_dispatcher(start, stop, num=None, endpoint=None, dtype=None,
Expand DownExpand Up@@ -461,7 +461,7 @@ def geomspace(start, stop, num=50, endpoint=True, dtype=None, axis=0):
if axis != 0:
result = _nx.moveaxis(result, 0, axis)

return result.astype(dtype, copy=False)
return result.astype(dtype, copy=None)


def _needs_add_docstring(obj):
Expand Down
14 changes: 9 additions & 5 deletionsnumpy/_core/multiarray.pyi
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -181,7 +181,7 @@ def array(
object: _ArrayType,
dtype: None = ...,
*,
copy: bool | _CopyMode = ...,
copy:None |bool | _CopyMode = ...,
order: _OrderKACF = ...,
subok: L[True],
ndmin: int = ...,
Expand All@@ -192,7 +192,7 @@ def array(
object: _ArrayLike[_SCT],
dtype: None = ...,
*,
copy: bool | _CopyMode = ...,
copy:None |bool | _CopyMode = ...,
order: _OrderKACF = ...,
subok: bool = ...,
ndmin: int = ...,
Expand All@@ -203,7 +203,7 @@ def array(
object: object,
dtype: None = ...,
*,
copy: bool | _CopyMode = ...,
copy:None |bool | _CopyMode = ...,
order: _OrderKACF = ...,
subok: bool = ...,
ndmin: int = ...,
Expand All@@ -214,7 +214,7 @@ def array(
object: Any,
dtype: _DTypeLike[_SCT],
*,
copy: bool | _CopyMode = ...,
copy:None |bool | _CopyMode = ...,
order: _OrderKACF = ...,
subok: bool = ...,
ndmin: int = ...,
Expand All@@ -225,7 +225,7 @@ def array(
object: Any,
dtype: DTypeLike,
*,
copy: bool | _CopyMode = ...,
copy:None |bool | _CopyMode = ...,
order: _OrderKACF = ...,
subok: bool = ...,
ndmin: int = ...,
Expand DownExpand Up@@ -485,6 +485,7 @@ def asarray(
order: _OrderKACF = ...,
*,
device: None | L["cpu"] = ...,
copy: None | bool = ...,
like: None | _SupportsArrayFunc = ...,
) -> NDArray[_SCT]: ...
@overload
Expand All@@ -494,6 +495,7 @@ def asarray(
order: _OrderKACF = ...,
*,
device: None | L["cpu"] = ...,
copy: None | bool = ...,
like: None | _SupportsArrayFunc = ...,
) -> NDArray[Any]: ...
@overload
Expand All@@ -503,6 +505,7 @@ def asarray(
order: _OrderKACF = ...,
*,
device: None | L["cpu"] = ...,
copy: None | bool = ...,
like: None | _SupportsArrayFunc = ...,
) -> NDArray[_SCT]: ...
@overload
Expand All@@ -512,6 +515,7 @@ def asarray(
order: _OrderKACF = ...,
*,
device: None | L["cpu"] = ...,
copy: None | bool = ...,
like: None | _SupportsArrayFunc = ...,
) -> NDArray[Any]: ...

Expand Down
4 changes: 2 additions & 2 deletionsnumpy/_core/numeric.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -526,7 +526,7 @@ def count_nonzero(a, axis=None, *, keepdims=False):
if np.issubdtype(a.dtype, np.character):
a_bool = a != a.dtype.type()
else:
a_bool = a.astype(np.bool, copy=False)
a_bool = a.astype(np.bool, copy=None)

return a_bool.sum(axis=axis, dtype=np.intp, keepdims=keepdims)

Expand DownExpand Up@@ -868,7 +868,7 @@ def convolve(a, v, mode='full'):
array([2.5])

"""
a, v = array(a, copy=False, ndmin=1), array(v, copy=False, ndmin=1)
a, v = array(a, copy=None, ndmin=1), array(v, copy=None, ndmin=1)
if (len(v) > len(a)):
a, v = v, a
if len(a) == 0:
Expand Down
2 changes: 1 addition & 1 deletionnumpy/_core/shape_base.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -552,7 +552,7 @@ def _block_check_depths_match(arrays, parent_index=[]):
def _atleast_nd(a, ndim):
# Ensures `a` has at least `ndim` dimensions by prepending
# ones to `a.shape` as necessary
return array(a, ndmin=ndim, copy=False, subok=True)
return array(a, ndmin=ndim, copy=None, subok=True)


def _accumulate(values):
Expand Down
5 changes: 2 additions & 3 deletionsnumpy/_core/src/multiarray/conversion_utils.c
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -229,9 +229,8 @@ PyArray_OptionalIntpConverter(PyObject *obj, PyArray_Dims *seq)
NPY_NO_EXPORT int
PyArray_CopyConverter(PyObject *obj, NPY_COPYMODE *copymode) {
if (obj == Py_None) {
PyErr_SetString(PyExc_ValueError,
"NoneType copy mode not allowed.");
return NPY_FAIL;
*copymode = NPY_COPY_IF_NEEDED;
return NPY_SUCCEED;
}

int int_copymode;
Expand Down
4 changes: 2 additions & 2 deletionsnumpy/_core/src/multiarray/conversion_utils.h
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,9 +13,9 @@ NPY_NO_EXPORT int
PyArray_OptionalIntpConverter(PyObject *obj, PyArray_Dims *seq);

typedef enum {
NPY_COPY_IF_NEEDED = 0,
NPY_COPY_NEVER = 0,
NPY_COPY_ALWAYS = 1,
NPY_COPY_NEVER = 2,
NPY_COPY_IF_NEEDED = 2,
} NPY_COPYMODE;

NPY_NO_EXPORT int
Expand Down
3 changes: 2 additions & 1 deletionnumpy/_core/src/multiarray/methods.c
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -831,7 +831,8 @@ array_astype(PyArrayObject *self,

if (forcecopy == NPY_COPY_NEVER) {
PyErr_SetString(PyExc_ValueError,
"Unable to avoid copy while casting in never copy mode.");
"Unable to avoid copy while casting in never copy mode. "
"Use copy=None to copy only if necessary.");
Py_DECREF(dtype);
return NULL;
}
Expand Down
6 changes: 3 additions & 3 deletionsnumpy/_core/src/multiarray/multiarraymodule.c
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -1828,7 +1828,7 @@ array_asanyarray(PyObject *NPY_UNUSED(ignored),
}

PyObject *res = _array_fromobject_generic(
op, dt_info.descr, dt_info.dtype,NPY_FALSE, order, NPY_TRUE, 0);
op, dt_info.descr, dt_info.dtype,NPY_COPY_IF_NEEDED, order, NPY_TRUE, 0);
Py_XDECREF(dt_info.descr);
Py_XDECREF(dt_info.dtype);
return res;
Expand DownExpand Up@@ -1869,7 +1869,7 @@ array_ascontiguousarray(PyObject *NPY_UNUSED(ignored),
}

PyObject *res = _array_fromobject_generic(
op, dt_info.descr, dt_info.dtype,NPY_FALSE, NPY_CORDER, NPY_FALSE,
op, dt_info.descr, dt_info.dtype,NPY_COPY_IF_NEEDED, NPY_CORDER, NPY_FALSE,
1);
Py_XDECREF(dt_info.descr);
Py_XDECREF(dt_info.dtype);
Expand DownExpand Up@@ -1911,7 +1911,7 @@ array_asfortranarray(PyObject *NPY_UNUSED(ignored),
}

PyObject *res = _array_fromobject_generic(
op, dt_info.descr, dt_info.dtype,NPY_FALSE, NPY_FORTRANORDER,
op, dt_info.descr, dt_info.dtype,NPY_COPY_IF_NEEDED, NPY_FORTRANORDER,
NPY_FALSE, 1);
Py_XDECREF(dt_info.descr);
Py_XDECREF(dt_info.dtype);
Expand Down
25 changes: 11 additions & 14 deletionsnumpy/_core/tests/test_api.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -177,18 +177,18 @@ def test_array_astype():
assert_equal(a, b)
assert_(not (a is b))

# copy=False parametercan sometimes skip a copy
# copy=False parameterskips a copy
b = a.astype('f4', copy=False)
assert_(a is b)

# order parameter allows overriding of the memory layout,
# forcing a copy if the layout is wrong
b = a.astype('f4', order='F', copy=False)
b = a.astype('f4', order='F', copy=None)
assert_equal(a, b)
assert_(not (a is b))
assert_(b.flags.f_contiguous)

b = a.astype('f4', order='C', copy=False)
b = a.astype('f4', order='C', copy=None)
assert_equal(a, b)
assert_(a is b)
assert_(b.flags.c_contiguous)
Expand All@@ -214,12 +214,12 @@ class MyNDArray(np.ndarray):
assert_(a is b)

# subok=True is default, and creates a subtype on a cast
b = a.astype('i4', copy=False)
b = a.astype('i4', copy=None)
assert_equal(a, b)
assert_equal(type(b), MyNDArray)

# subok=False never returns a subclass
b = a.astype('f4', subok=False, copy=False)
b = a.astype('f4', subok=False, copy=None)
assert_equal(a, b)
assert_(not (a is b))
assert_(type(b) is not MyNDArray)
Expand DownExpand Up@@ -536,9 +536,9 @@ def check_contig(a, ccontig, fcontig):
check_contig(np.empty((2, 2), order='F'), False, True)

# Check that np.array creates correct contiguous flags:
check_contig(np.array(a, copy=False), False, False)
check_contig(np.array(a, copy=False, order='C'), True, False)
check_contig(np.array(a, ndmin=4, copy=False, order='F'), False, True)
check_contig(np.array(a, copy=None), False, False)
check_contig(np.array(a, copy=None, order='C'), True, False)
check_contig(np.array(a, ndmin=4, copy=None, order='F'), False, True)

# Check slicing update of flags and :
check_contig(a[0], True, True)
Expand DownExpand Up@@ -577,18 +577,15 @@ def test_astype_copyflag():
res_false = arr.astype(np.intp, copy=False)
# `res_false is arr` currently, but check `may_share_memory`.
assert np.may_share_memory(arr, res_false)
res_if_needed = arr.astype(np.intp, copy=np._CopyMode.IF_NEEDED)
res_if_needed = arr.astype(np.intp, copy=None)
# `res_if_needed is arr` currently, but check `may_share_memory`.
assert np.may_share_memory(arr, res_if_needed)

res_never = arr.astype(np.intp, copy=np._CopyMode.NEVER)
assert np.may_share_memory(arr, res_never)

# Simple tests for when a copy is necessary:
res_false = arr.astype(np.float64, copy=False)
assert_array_equal(res_false, arr)
res_if_needed = arr.astype(np.float64,
copy=np._CopyMode.IF_NEEDED)
res_if_needed = arr.astype(np.float64, copy=None)
assert_array_equal(res_if_needed, arr)
assert_raises(ValueError, arr.astype, np.float64,
copy=np._CopyMode.NEVER)
copy=False)
Loading

[8]ページ先頭

©2009-2025 Movatter.jp