From e9b771ba555611ca6ff8da22bd33d8b213b240f6 Mon Sep 17 00:00:00 2001 From: Pieter Eendebak Date: Fri, 11 Apr 2025 23:51:45 +0200 Subject: [PATCH 1/2] ENH: Performance improvement for astype --- numpy/_core/src/multiarray/scalartypes.c.src | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/numpy/_core/src/multiarray/scalartypes.c.src b/numpy/_core/src/multiarray/scalartypes.c.src index 39909c159683..723294ba1fda 100644 --- a/numpy/_core/src/multiarray/scalartypes.c.src +++ b/numpy/_core/src/multiarray/scalartypes.c.src @@ -2131,7 +2131,7 @@ gentype_byteswap(PyObject *self, PyObject *args, PyObject *kwds) * * #name = take, getfield, put, repeat, tofile, mean, trace, diagonal, clip, * std, var, sum, cumsum, prod, cumprod, compress, sort, argsort, - * round, argmax, argmin, max, min, any, all, astype, resize, + * round, argmax, argmin, max, min, any, all, resize, * reshape, choose, tostring, tobytes, copy, searchsorted, view, * flatten, ravel, squeeze# */ @@ -2142,6 +2142,22 @@ gentype_@name@(PyObject *self, PyObject *args, PyObject *kwds) } /**end repeat**/ +static PyObject * +gentype_astype(PyObject *self, PyObject *args, PyObject *kwds) +{ + if ((kwds == NULL) && (PyTuple_Size(args)==1)) { + // no keyword arguments, single argument is the dtype + PyArray_Descr *dtype = PyArray_DescrFromScalar(self); + assert(dtype != NULL); + int same_dtype = ( (PyObject *)dtype == PyTuple_GET_ITEM(args, 0)); + Py_DECREF(dtype); + if (same_dtype) { + // dtypes are equal, scalars are immutable so no copy is needed + return Py_NewRef(self); + } + } + return gentype_generic_method(self, args, kwds, "astype"); +} /**begin repeat * #name = integer, floating# From 202dc21ed227697ca78001b55c83bf102345c7bd Mon Sep 17 00:00:00 2001 From: Pieter Eendebak Date: Fri, 11 Apr 2025 23:59:11 +0200 Subject: [PATCH 2/2] update doc --- numpy/_core/_add_newdocs.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/numpy/_core/_add_newdocs.py b/numpy/_core/_add_newdocs.py index 90b3d91d9578..3cdfccaf4a4c 100644 --- a/numpy/_core/_add_newdocs.py +++ b/numpy/_core/_add_newdocs.py @@ -3202,7 +3202,7 @@ copy : bool, optional By default, astype always returns a newly allocated array. If this is set to false, and the `dtype`, `order`, and `subok` - requirements are satisfied, the input array is returned instead + requirements are satisfied, the input array may be returned instead of a copy. Returns