Skip to content

WIP: correct maximum element space calculation in array2string #9144

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
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
32 changes: 24 additions & 8 deletions numpy/core/arrayprint.py
Original file line number Diff line number Diff line change
Expand Up @@ -245,12 +245,6 @@ def _leading_trailing(a):
b = _nc.concatenate(tuple(l))
return b

def _boolFormatter(x):
if x:
return ' True'
else:
return 'False'

def _object_format(o):
""" Object arrays containing lists should be printed unambiguously """
if type(o) is list:
Expand All @@ -264,7 +258,7 @@ def repr_format(x):

def _get_formatdict(data, precision, suppress_small, formatter):
# wrapped in lambdas to avoid taking a code path with the wrong type of data
formatdict = {'bool': lambda: _boolFormatter,
formatdict = {'bool': lambda: BoolFormat(data),
'int': lambda: IntegerFormat(data),
'float': lambda: FloatFormat(data, precision, suppress_small),
'longfloat': lambda: LongFloatFormat(precision),
Expand Down Expand Up @@ -626,7 +620,8 @@ def fillFormat(self, data):
with _nc.errstate(all='ignore'):
special = isnan(data) | isinf(data)
valid = not_equal(data, 0) & ~special
non_zero = absolute(data.compress(valid))
valid_data = data.compress(valid)
non_zero = absolute(valid_data)
if len(non_zero) == 0:
max_val = 0.
min_val = 0.
Expand All @@ -648,6 +643,8 @@ def fillFormat(self, data):
format = '%+'
else:
format = '%'
if not np.any(np.signbit(valid_data)):
self.max_str_len -= 1
format = format + '%d.%de' % (self.max_str_len, self.precision)
else:
format = '%%.%df' % (self.precision,)
Expand All @@ -666,6 +663,8 @@ def fillFormat(self, data):
format = '%#+'
else:
format = '%#'
if not np.any(np.signbit(valid_data)):
self.max_str_len -= 1
format = format + '%d.%df' % (self.max_str_len, precision)

self.special_fmt = '%%%ds' % (self.max_str_len,)
Expand Down Expand Up @@ -714,6 +713,23 @@ def _digits(x, precision, format):
return 0


class BoolFormat(object):
def __init__(self, data):
try:
max_str_len = 4 if all(data) else 5
self.format = '%' + str(max_str_len) + 's'
except (TypeError, NotImplementedError):
# if reduce(data) fails, this instance will not be called, just
# instantiated in formatdict.
pass
except ValueError:
# this occurs when everything is NA
pass

def __call__(self, x):
return self.format % ('True' if x else 'False')


class IntegerFormat(object):
def __init__(self, data):
try:
Expand Down