8000 BUG: infinite recursion in str of 0d subclasses · numpy/numpy@6a05fea · GitHub
[go: up one dir, main page]

Skip to content

Commit 6a05fea

Browse files
ahaldanecharris
authored andcommitted
BUG: infinite recursion in str of 0d subclasses
Fixes #10360
1 parent 7311b96 commit 6a05fea

File tree

2 files changed

+63
-6
lines changed

2 files changed

+63
-6
lines changed

numpy/core/arrayprint.py

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -435,14 +435,17 @@ def wrapper(self, *args, **kwargs):
435435
# gracefully handle recursive calls, when object arrays contain themselves
436436
@_recursive_guard()
437437
def _array2string(a, options, separator=' ', prefix=""):
438-
# The formatter __init__s cannot deal with subclasses yet
439-
data = asarray(a)
438+
# The formatter __init__s in _get_format_function cannot deal with
439+
# subclasses yet, and we also need to avoid recursion issues in
440+
# _formatArray with subclasses which return 0d arrays in place of scalars
441+
a = asarray(a)
440442

441443
if a.size > options['threshold']:
442444
summary_insert = "..."
443-
data = _leading_trailing(data, options['edgeitems'])
445+
data = _leading_trailing(a, options['edgeitems'])
444446
else:
445447
summary_insert = ""
448+
data = a
446449

447450
# find the right formatting function for the array
448451
format_function = _get_format_function(data, **options)
@@ -468,7 +471,7 @@ def array2string(a, max_line_width=None, precision=None,
468471
469472
Parameters
470473
----------
471-
a : ndarray
474+
a : array_like
472475
Input array.
473476
max_line_width : int, optional
474477
The maximum number of columns the string should span. Newline
@@ -730,7 +733,7 @@ def recurser(index, hanging_indent, curr_width):
730733

731734
if show_summary:
732735
if legacy == '1.13':
733-
# trailing space, fixed number of newlines, and fixed separator
736+
# trailing space, fixed nbr of newlines, and fixed separator
734737
s += hanging_indent + summary_insert + ", \n"
735738
else:
736739
s += hanging_indent + summary_insert + line_sep
@@ -1380,6 +1383,8 @@ def array_repr(arr, max_line_width=None, precision=None, suppress_small=None):
13801383

13811384
return arr_str + spacer + dtype_str
13821385

1386+
_guarded_str = _recursive_guard()(str)
1387+
13831388
def array_str(a, max_line_width=None, precision=None, suppress_small=None):
13841389
"""
13851390
Return a string representation of the data in an array.
@@ -1422,7 +1427,10 @@ def array_str(a, max_line_width=None, precision=None, suppress_small=None):
14221427
# so floats are not truncated by `precision`, and strings are not wrapped
14231428
# in quotes. So we return the str of the scalar value.
14241429
if a.shape == ():
1425-
return str(a[()])
1430+
# obtain a scalar and call str on it, avoiding problems for subclasses
1431+
# for which indexing with () returns a 0d instead of a scalar by using
1432+
# ndarray's getindex. Also guard against recursive 0d object arrays.
1433+
return _guarded_str(np.ndarray.__getitem__(a, ()))
14261434

14271435
return array2string(a, max_line_width, precision, suppress_small, ' ', "")
14281436

numpy/core/tests/test_arrayprint.py

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,55 @@ class sub(np.ndarray): pass
3434
" [(1,), (1,)]], dtype=[('a', '<i4')])"
3535
)
3636

37+
def test_0d_object_subclass(self):
38+
# make sure that subclasses which return 0ds instead
39+
# of scalars don't cause infinite recursion in str
40+
class sub(np.ndarray):
41+
def __new__(cls, inp):
42+
obj = np.asarray(inp).view(cls)
43+
return obj
44+
45+
def __getitem__(self, ind):
46+
ret = super(sub, self).__getitem__(ind)
47+
return sub(ret)
48+
49+
x = sub(1)
50+
assert_equal(repr(x), 'sub(1)')
51+
assert_equal(str(x), '1')
52+
53+
x = sub([1, 1])
54+
assert_equal(repr(x), 'sub([1, 1])')
55+
assert_equal(str(x), '[1 1]')
56+
57+
# check it works properly with object arrays too
58+
x = sub(None)
59+
assert_equal(repr(x), 'sub(None, dtype=object)')
60+
assert_equal(str(x), 'None')
61+
62+
# plus recursive object arrays (even depth > 1)
63+
y = sub(None)
64+
x[()] = y
65+
y[()] = x
66+
assert_equal(repr(x),
67+
'sub(sub(sub(..., dtype=object), dtype=object), dtype=object)')
68+
assert_equal(str(x), '...')
69+
70+
# nested 0d-subclass-object
71+
x = sub(None)
72+
x[()] = sub(None)
73+
assert_equal(repr(x), 'sub(sub(None, dtype=object), dtype=object)')
74+
assert_equal(str(x), 'None')
75+
76+
# test that object + subclass is OK:
77+
x = sub([None, None])
78+
assert_equal(repr(x), 'sub([None, None], dtype=object)')
79+
assert_equal(str(x), '[None None]')
80+
81+
x = sub([None, sub([None, None])])
82+
assert_equal(repr(x),
83+
'sub([None, sub([None, None], dtype=object)], dtype=object)')
84+
assert_equal(str(x), '[None sub([None, None], dtype=object)]')
85+
3786
def test_self_containing(self):
3887
arr0d = np.array(None)
3988
arr0d[()] = arr0d

0 commit comments

Comments
 (0)
0