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

Appearance settings

Commit 10f62a0

Browse filesBrowse files
ngoldbaumcharris
authored andcommitted
BUG: use PyArray_SafeCast in array_astype
1 parent cae7f62 commit 10f62a0
Copy full SHA for 10f62a0

File tree

Expand file treeCollapse file tree

2 files changed

+18
-7
lines changed
Filter options
Expand file treeCollapse file tree

2 files changed

+18
-7
lines changed

‎numpy/_core/src/multiarray/methods.c

Copy file name to clipboardExpand all lines: numpy/_core/src/multiarray/methods.c
+11-7Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -811,8 +811,8 @@ array_astype(PyArrayObject *self,
811811

812812
/*
813813
* If the memory layout matches and, data types are equivalent,
814-
* and it's not a subtype if subok is False, then we
815-
* can skip the copy.
814+
* it's not a subtype if subok is False, and if the cast says
815+
* view are possible, we can skip the copy.
816816
*/
817817
if (forcecopy != NPY_AS_TYPE_COPY_ALWAYS &&
818818
(order == NPY_KEEPORDER ||
@@ -823,11 +823,15 @@ array_astype(PyArrayObject *self,
823823
PyArray_IS_C_CONTIGUOUS(self)) ||
824824
(order == NPY_FORTRANORDER &&
825825
PyArray_IS_F_CONTIGUOUS(self))) &&
826-
(subok || PyArray_CheckExact(self)) &&
827-
PyArray_EquivTypes(dtype, PyArray_DESCR(self))) {
828-
Py_DECREF(dtype);
829-
Py_INCREF(self);
830-
return (PyObject *)self;
826+
(subok || PyArray_CheckExact(self))) {
827+
npy_intp view_offset;
828+
npy_intp is_safe = PyArray_SafeCast(dtype, PyArray_DESCR(self),
829+
&view_offset, NPY_NO_CASTING, 1);
830+
if (is_safe && (view_offset != NPY_MIN_INTP)) {
831+
Py_DECREF(dtype);
832+
Py_INCREF(self);
833+
return (PyObject *)self;
834+
}
831835
}
832836

833837
if (!PyArray_CanCastArrayTo(self, dtype, casting)) {

‎numpy/_core/tests/test_stringdtype.py

Copy file name to clipboardExpand all lines: numpy/_core/tests/test_stringdtype.py
+7Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -497,6 +497,13 @@ def test_create_with_copy_none(string_list):
497497
assert arr_view is arr
498498

499499

500+
def test_astype_copy_false():
501+
orig_dt = StringDType()
502+
arr = np.array(["hello", "world"], dtype=StringDType())
503+
assert not arr.astype(StringDType(coerce=False), copy=False).dtype.coerce
504+
505+
assert arr.astype(orig_dt, copy=False).dtype is orig_dt
506+
500507
@pytest.mark.parametrize(
501508
"strings",
502509
[

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.