Skip to content

Commit df0b1bd

Browse files
authored
Merge pull request numpy#19888 from WarrenWeckesser/emptylikezerostrides
BUG: core: Fix *_like strides for str and bytes dtype.
2 parents 19caf5b + ee885f2 commit df0b1bd

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

numpy/core/src/multiarray/ctors.c

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1020,6 +1020,17 @@ PyArray_NewLikeArrayWithShape(PyArrayObject *prototype, NPY_ORDER order,
10201020

10211021
/* Build the new strides */
10221022
stride = dtype->elsize;
1023+
if (stride == 0 && PyDataType_ISSTRING(dtype)) {
1024+
/* Special case for dtype=str or dtype=bytes. */
1025+
if (dtype->type_num == NPY_STRING) {
1026+
/* dtype is bytes */
1027+
stride = 1;
1028+
}
1029+
else {
1030+
/* dtype is str (type_num is NPY_UNICODE) */
1031+
stride = 4;
1032+
}
1033+
}
10231034
for (idim = ndim-1; idim >= 0; --idim) {
10241035
npy_intp i_perm = strideperm[idim].perm;
10251036
strides[i_perm] = stride;

numpy/core/tests/test_numeric.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2893,6 +2893,21 @@ def test_filled_like(self):
28932893
self.check_like_function(np.full_like, 123.456, True)
28942894
self.check_like_function(np.full_like, np.inf, True)
28952895

2896+
@pytest.mark.parametrize('likefunc', [np.empty_like, np.full_like,
2897+
np.zeros_like, np.ones_like])
2898+
@pytest.mark.parametrize('dtype', [str, bytes])
2899+
def test_dtype_str_bytes(self, likefunc, dtype):
2900+
# Regression test for gh-19860
2901+
a = np.arange(16).reshape(2, 8)
2902+
b = a[:, ::2] # Ensure b is not contiguous.
2903+
kwargs = {'fill_value': ''} if likefunc == np.full_like else {}
2904+
result = likefunc(b, dtype=dtype, **kwargs)
2905+
if dtype == str:
2906+
assert result.strides == (16, 4)
2907+
else:
2908+
# dtype is bytes
2909+
assert result.strides == (4, 1)
2910+
28962911

28972912
class TestCorrelate:
28982913
def _setup(self, dt):

0 commit comments

Comments
 (0)