diff options
author | Charles Harris <charlesr.harris@gmail.com> | 2021-09-18 13:26:22 -0600 |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-09-18 13:26:22 -0600 |
commit | df0b1bd75f0e8489912863d1f9dfde1846a7bf51 (patch) | |
tree | 9fafebf51611b98359ba3f5d8cfb55dcc277de50 | |
parent | 19caf5b821ccbdd8b6f8d05ac5a3517c2dbd33f8 (diff) | |
parent | ee885f247cf866db439117c1160a3048274ea9a0 (diff) | |
download | numpy-df0b1bd75f0e8489912863d1f9dfde1846a7bf51.tar.gz |
Merge pull request #19888 from WarrenWeckesser/emptylikezerostrides
BUG: core: Fix *_like strides for str and bytes dtype.
-rw-r--r-- | numpy/core/src/multiarray/ctors.c | 11 | ||||
-rw-r--r-- | numpy/core/tests/test_numeric.py | 15 |
2 files changed, 26 insertions, 0 deletions
diff --git a/numpy/core/src/multiarray/ctors.c b/numpy/core/src/multiarray/ctors.c index 73d864a4d..04be45f00 100644 --- a/numpy/core/src/multiarray/ctors.c +++ b/numpy/core/src/multiarray/ctors.c @@ -1020,6 +1020,17 @@ PyArray_NewLikeArrayWithShape(PyArrayObject *prototype, NPY_ORDER order, /* Build the new strides */ stride = dtype->elsize; + if (stride == 0 && PyDataType_ISSTRING(dtype)) { + /* Special case for dtype=str or dtype=bytes. */ + if (dtype->type_num == NPY_STRING) { + /* dtype is bytes */ + stride = 1; + } + else { + /* dtype is str (type_num is NPY_UNICODE) */ + stride = 4; + } + } for (idim = ndim-1; idim >= 0; --idim) { npy_intp i_perm = strideperm[idim].perm; strides[i_perm] = stride; diff --git a/numpy/core/tests/test_numeric.py b/numpy/core/tests/test_numeric.py index 19de0a8aa..4510333a1 100644 --- a/numpy/core/tests/test_numeric.py +++ b/numpy/core/tests/test_numeric.py @@ -2893,6 +2893,21 @@ class TestLikeFuncs: self.check_like_function(np.full_like, 123.456, True) self.check_like_function(np.full_like, np.inf, True) + @pytest.mark.parametrize('likefunc', [np.empty_like, np.full_like, + np.zeros_like, np.ones_like]) + @pytest.mark.parametrize('dtype', [str, bytes]) + def test_dtype_str_bytes(self, likefunc, dtype): + # Regression test for gh-19860 + a = np.arange(16).reshape(2, 8) + b = a[:, ::2] # Ensure b is not contiguous. + kwargs = {'fill_value': ''} if likefunc == np.full_like else {} + result = likefunc(b, dtype=dtype, **kwargs) + if dtype == str: + assert result.strides == (16, 4) + else: + # dtype is bytes + assert result.strides == (4, 1) + class TestCorrelate: def _setup(self, dt): |