Skip to content

Commit 4faf84e

Browse files
committed
MAINT: refactor array_repr to treat shape and dtype similary
To help set oneself up for using shape for different reasons.
1 parent a83bc02 commit 4faf84e

File tree

1 file changed

+17
-19
lines changed

1 file changed

+17
-19
lines changed

numpy/_core/arrayprint.py

Lines changed: 17 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1578,39 +1578,37 @@ def _array_repr_implementation(
15781578
else:
15791579
class_name = "array"
15801580

1581-
skipdtype = dtype_is_implied(arr.dtype) and arr.size > 0
1582-
15831581
prefix = class_name + "("
1584-
suffix = ")" if skipdtype else ","
1585-
15861582
if (current_options['legacy'] <= 113 and
15871583
arr.shape == () and not arr.dtype.names):
15881584
lst = repr(arr.item())
1589-
elif arr.size > 0 or arr.shape == (0,):
1585+
else:
15901586
lst = array2string(arr, max_line_width, precision, suppress_small,
1591-
', ', prefix, suffix=suffix)
1592-
else: # show zero-length shape unless it is (0,)
1593-
lst = "[], shape=%s" % (repr(arr.shape),)
1594-
1595-
arr_str = prefix + lst + suffix
1587+
', ', prefix, suffix=")")
15961588

1597-
if skipdtype:
1598-
return arr_str
1589+
extras = []
1590+
if not dtype_is_implied(arr.dtype) or arr.size == 0:
1591+
extras.append(f"dtype={dtype_short_repr(arr.dtype)}")
1592+
if arr.size == 0 and arr.shape != (0,):
1593+
extras.append(f"{shape=}")
15991594

1600-
dtype_str = "dtype={})".format(dtype_short_repr(arr.dtype))
1595+
if not extras:
1596+
return prefix + lst + ")"
16011597

1602-
# compute whether we should put dtype on a new line: Do so if adding the
1603-
# dtype would extend the last line past max_line_width.
1598+
arr_str = prefix + lst + ","
1599+
extra_str = ", ".join(extras) + ")"
1600+
# compute whether we should put extras on a new line: Do so if adding the
1601+
# extras would extend the last line past max_line_width.
16041602
# Note: This line gives the correct result even when rfind returns -1.
16051603
last_line_len = len(arr_str) - (arr_str.rfind('\n') + 1)
16061604
spacer = " "
16071605
if current_options['legacy'] <= 113:
16081606
if issubclass(arr.dtype.type, flexible):
1609-
spacer = '\n' + ' '*len(class_name + "(")
1610-
elif last_line_len + len(dtype_str) + 1 > max_line_width:
1611-
spacer = '\n' + ' '*len(class_name + "(")
1607+
spacer = '\n' + ' '*len(prefix)
1608+
elif last_line_len + len(extra_str) + 1 > max_line_width:
1609+
spacer = '\n' + ' '*len(prefix)
16121610

1613-
return arr_str + spacer + dtype_str
1611+
return arr_str + spacer + extra_str
16141612

16151613

16161614
def _array_repr_dispatcher(

0 commit comments

Comments
 (0)