Skip to content

Commit 54487a8

Browse files
committed
BUG: Don't call str when constructing unicode arrays
Fixes #5049
1 parent aa746c6 commit 54487a8

2 files changed

Lines changed: 37 additions & 0 deletions

File tree

‎numpy/core/src/multiarray/arraytypes.c.src‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -426,6 +426,20 @@ UNICODE_setitem(PyObject *op, void *ov, void *vap)
426426
char *buffer;
427427
#endif
428428

429+
/* Handle case of assigning from an array scalar */
430+
if (PyArray_Check(op) && PyArray_NDIM((PyArrayObject *)op) == 0) {
431+
temp = PyArray_ToScalar(PyArray_BYTES((PyArrayObject *)op),
432+
(PyArrayObject *)op);
433+
if (temp == NULL) {
434+
return -1;
435+
}
436+
else {
437+
int res = UNICODE_setitem(temp, ov, ap);
438+
Py_DECREF(temp);
439+
return res;
440+
}
441+
}
442+
429443
if (!PyBytes_Check(op) && !PyUnicode_Check(op) &&
430444
PySequence_Check(op) && PySequence_Size(op) > 0) {
431445
PyErr_SetString(PyExc_ValueError,

‎numpy/core/tests/test_multiarray.py‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
import ctypes
1313
import os
1414
import gc
15+
from contextlib import contextmanager
1516
if sys.version_info[0] >= 3:
1617
import builtins
1718
else:
@@ -381,6 +382,28 @@ def assign(v):
381382
assert_raises((AttributeError, TypeError), assign, C())
382383
assert_raises(ValueError, assign, [1])
383384

385+
def test_unicode_assignment(self):
386+
# gh-5049
387+
from numpy.core.numeric import set_string_function
388+
389+
@contextmanager
390+
def inject_str(s):
391+
""" replace ndarray.__str__ temporarily """
392+
set_string_function(lambda x: s, repr=False)
393+
try:
394+
yield
395+
finally:
396+
set_string_function(None, repr=False)
397+
398+
a1d = np.array([u'test'])
399+
a0d = np.array(u'done')
400+
with inject_str(u'bad'):
401+
a1d[0] = a0d # previously this would invoke __str__
402+
assert_equal(a1d[0], u'done')
403+
404+
# this would crash for the same reason
405+
np.array([np.array(u'\xe5\xe4\xf6')])
406+
384407

385408
class TestDtypedescr(TestCase):
386409
def test_construction(self):

0 commit comments

Comments
 (0)