Skip to content

ENH: Print funny-shaped empty arrays using "empty" #10119

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 20 additions & 10 deletions numpy/core/arrayprint.py
Original file line number Diff line number Diff line change
Expand Up @@ -1252,25 +1252,35 @@ def array_repr(arr, max_line_width=None, precision=None, suppress_small=None):
if max_line_width is None:
max_line_width = _format_options['linewidth']

# determine class name
if type(arr) is not ndarray:
class_name = type(arr).__name__
else:
class_name = "array"

if (_format_options['legacy'] == '1.13' and
arr.shape == () and not arr.dtype.names):
lst = repr(arr.item())
elif arr.size > 0 or arr.shape == (0,):
# determine dtype name
typename = dtype_short_repr(arr.dtype)

# stringify the array elements and take care of empty arrays
if _format_options['legacy'] == '1.13':
if arr.shape == () and not arr.dtype.names:
lst = repr(arr.item())
elif arr.size > 0 or arr.shape == (0,):
lst = array2string(arr, max_line_width, precision, suppress_small,
', ', class_name + "(")
else: # show zero-length shape unless it is (0,)
lst = "[], shape=%s" % (repr(arr.shape),)
else:
# print empty arrays with an unusual shapes using "empty"
if arr.size == 0 and arr.shape != (0,):
return "empty({}, dtype={})".format(arr.shape, typename)

lst = array2string(arr, max_line_width, precision, suppress_small,
', ', class_name + "(")
else: # show zero-length shape unless it is (0,)
lst = "[], shape=%s" % (repr(arr.shape),)

skipdtype = dtype_is_implied(arr.dtype) and arr.size > 0

if skipdtype:
# skip the dtype if it's not needed
if dtype_is_implied(arr.dtype) and arr.size > 0:
return "%s(%s)" % (class_name, lst)
typename = dtype_short_repr(arr.dtype)

prefix = "{}({},".format(class_name, lst)
suffix = "dtype={})".format(typename)
Expand Down
9 changes: 9 additions & 0 deletions numpy/core/tests/test_arrayprint.py
Original file line number Diff line number Diff line change
Expand Up @@ -502,6 +502,15 @@ def test_dtype_linewidth_wrapping(self):
array(['1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1'],
dtype='{}')""".format(styp)))

def test_empty(self):
assert_equal(repr(np.ones((0,))), "array([], dtype=float64)")
assert_equal(repr(np.ones((2,0))), "empty((2, 0), dtype=float64)")
np.set_printoptions(legacy='1.13')
assert_equal(repr(np.ones((0,))), "array([], dtype=float64)")
assert_equal(repr(np.ones((2,0))),
"array([], shape=(2, 0), dtype=float64)")


def test_unicode_object_array():
import sys
if sys.version_info[0] >= 3:
Expand Down
6 changes: 5 additions & 1 deletion numpy/ma/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -3908,6 +3908,8 @@ def __repr__(self):
self.size == 0
)

is_ndim_empty = self.size == 0 and len(self.shape) > 1
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: self.ndim


# determine which keyword args need to be shown
keys = ['data', 'mask', 'fill_value']
if dtype_needed:
Expand All @@ -3918,7 +3920,7 @@ def __repr__(self):

# choose what to indent each keyword with
min_indent = 2
if is_one_row:
if is_one_row or is_ndim_empty:
# first key on the same line as the type, remaining keys
# aligned by equals
indents = {}
Expand All @@ -3945,6 +3947,8 @@ def __repr__(self):
reprs['fill_value'] = repr(self.fill_value)
if dtype_needed:
reprs['dtype'] = np.core.arrayprint.dtype_short_repr(self.dtype)
if is_ndim_empty:
reprs['data'] = 'empty({})'.format(self.shape)

# join keys with values and indentations
result = ',\n'.join(
Expand Down
11 changes: 10 additions & 1 deletion numpy/ma/tests/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -555,7 +555,15 @@ def test_str_repr(self):
fill_value=999999)''')
)


# empty arrays with unusual shapes display it
assert_equal(
repr(array(np.empty((0,2), dtype='f8'))),
textwrap.dedent('''\
masked_array(data=empty((0, 2)),
mask=False,
fill_value=1e+20,
dtype=float64)''')
)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add a test for non-unusual shapes too?


def test_str_repr_legacy(self):
oldopts = np.get_printoptions()
Expand All @@ -575,6 +583,7 @@ def test_str_repr_legacy(self):
' mask = [False True True ... False False False],\n'
' fill_value = 999999)\n'
)

finally:
np.set_printoptions(**oldopts)

Expand Down