8000 ENH: remove unneeded spaces in float/bool reprs, fixes 0d str by ahaldane · Pull Request #9139 · numpy/numpy · GitHub
[go: up one dir, main page]

Skip to content

ENH: remove unneeded spaces in float/bool reprs, fixes 0d str #9139

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

Merged
merged 6 commits into from
Sep 26, 2017
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
MAINT: fixups to legacy spacing in FloatFormat
  • Loading branch information
ahaldane committed Sep 26, 2017
commit 710e0327687b9f7653e5ac02d222ba62c657a718
20 changes: 5 additions & 15 deletions doc/release/1.14.0-notes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -310,25 +310,15 @@ This option controls printing of the sign of floating-point types, and may be
one of the characters '-', '+' or ' ', or the string 'legacy'. With '+' numpy
always prints the sign of positive values, with ' ' it always prints a space
(whitespace character) in the sign position of positive values, and with '-' it
will omit the sign character for positive values. The new default is '-'.
will omit the sign character for positive values, and with 'legacy' it will
behave like ' ' except no space is printed in 0d arrays. The new default is '-'.

Setting ``sign='legacy'`` will behave like ' ' except that no space is printed
in 0d arrays, and also includes a space before ``True`` values in size-1 bool
arrays. This approximates the behavior of numpy 1.13 and before.

Unneeded whitespace in float and bool array printing removed
------------------------------------------------------------
Unneeded whitespace in float array printing removed
---------------------------------------------------
The new default of ``sign='-'`` (see last note) means that the ``repr`` of
float arrays now often omits the whitespace characters previously used to
display the sign. This new behavior can be disabled to mostly reproduce numpy
1.13 behavior by calling:

>>> np.set_printoptions(sign='legacy')

Additionally, the ``repr`` of bool arrays with only one element now omits the
whitespace before a ``True`` value, so that ``repr(array([True]))`` now returns
``'array([True])'`` instead of ``'array([ True])'``. This is disabled by
setting ``sign='legacy'``.
1.13 behavior by calling ``np.set_printoptions(sign='legacy')``.

``threshold`` and ``edgeitems`` options added to ``np.array2string``
-----------------------------------------------------------------
Expand Down
35 changes: 12 additions & 23 deletions numpy/core/arrayprint.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,8 +119,7 @@ def set_printoptions(precision=None, threshold=None, edgeitems=None,
print the sign of positive values. If ' ', always prints a space
(whitespace character) in the sign position of positive values. If
'-', omit the sign character of positive values. If 'legacy', print a
space for positive values except in 0d arrays, and also add a space for
'True' values in size-1 bool arrays. (default '-')
space for positive values except in 0d arrays. (default '-')
formatter : dict of callables, optional
If not None, the keys should indicate the type(s) that the respective
formatting function applies to. Callables should return a string.
Expand Down Expand Up @@ -263,7 +262,7 @@ def _get_formatdict(data, **opt):
prec, supp, sign = opt['precision'], opt['suppress'], opt['sign']

# wrapped in lambdas to avoid taking a code path with the wrong type of data
formatdict = {'bool': lambda: BoolFormat(data, legacy=(sign == 'legacy')),
formatdict = {'bool': lambda: BoolFormat(data),
'int': lambda: IntegerFormat(data),
'float': lambda: FloatFormat(data, prec, supp, sign),
'longfloat': lambda: LongFloatFormat(prec),
Expand Down Expand Up @@ -379,7 +378,6 @@ def wrapper(self, *args, **kwargs):
# gracefully handle recursive calls, when object arrays contain themselves
@_recursive_guard()
def _array2string(a, options, separator=' ', prefix=""):

if a.size > options['threshold']:
summary_insert = "..., "
data = _leading_trailing(a)
Expand All @@ -401,7 +399,6 @@ def _array2string(a, options, separator=' ', prefix=""):
return lst



def array2string(a, max_line_width=None, precision=None,
suppress_small=None, separator=' ', prefix="",
style=np._NoValue, formatter=None, t 10000 hreshold=None,
Expand Down Expand Up @@ -471,8 +468,7 @@ def array2string(a, max_line_width=None, precision=None,
print the sign of positive values. If ' ', always prints a space
(whitespace character) in the sign position of positive values. If
'-', omit the sign character of positive values. If 'legacy', print a
space for positive values except in 0d arrays, and also add a space for
'True' values in size-1 bool arrays.
space for positive values except in 0d arrays.

Returns
-------
Expand Down Expand Up @@ -613,20 +609,18 @@ def __init__(self, data, precision, suppress_small, sign=False):
if isinstance(sign, bool):
sign = '+' if sign else '-'

self._legacy = False
if sign == 'legacy':
self._legacy = True
sign = '-' if data.shape == () else ' '

self.precision = precision
self.suppress_small = suppress_small
self.sign = sign
self.exp_format = False
self.large_exponent = False
try:
self.fillFormat(data)
except (NotImplementedError):
# if reduce(data) fails, this instance will not be called, just
# instantiated in formatdict.
pass

self.fillFormat(data)

def fillFormat(self, data):
with errstate(all='ignore'):
Expand All @@ -653,8 +647,9 @@ def fillFormat(self, data):
self.large_exponent = 0 < min_val < 1e-99 or max_val >= 1e100

signpos = self.sign != '-' or any(non_zero < 0)
# for back-compatibility with np 1.13, add extra space if padded
signpos = signpos if self.sign != ' ' else 2
# for back-compatibility with np 1.13, use two spaces
if self._legacy:
signpos = 2
max_str_len = signpos + 6 + self.precision + self.large_exponent

conversion = '' if self.sign == '-' else self.sign
Expand Down Expand Up @@ -739,15 +734,9 @@ def __call__(self, x):

class BoolFormat(object):
def __init__(self, data, **kwargs):
# in legacy printing style, include a space before True except in 0d
if kwargs.get('legacy', False):
self.truestr = ' True' if data.shape != () else 'True'
return

# add an extra space so " True" and "False" have the same length and
# array elements align nicely when printed, but only for arrays with
# more than one element (0d and nd)
self.truestr = ' True' if data.size > 1 else 'True'
# array elements align nicely when printed, except in 0d arrays
self.truestr = ' True' if data.shape != () else 'True'

def __call__(self, x):
return self.truestr if x else "False"
Expand Down
8 changes: 7 additions & 1 deletion numpy/core/tests/test_arrayprint.py
Original file line number Diff line number Diff line change
Expand Up @@ -274,28 +274,34 @@ def test_bool_spacing(self):
assert_equal(repr(np.array([True, False])),
'array([ True, False], dtype=bool)')
assert_equal(repr(np.array([True])),
'array([True], dtype=bool)')
'array([ True], dtype=bool)')
assert_equal(repr(np.array(True)),
'array(True, dtype=bool)')
assert_equal(repr(np.array(False)),
'array(False, dtype=bool)')

def test_sign_spacing(self):
a = np.arange(4.)
b = np.array([1.234e9])

assert_equal(repr(a), 'array([0., 1., 2., 3.])')
assert_equal(repr(np.array(1.)), 'array(1.)')
assert_equal(repr(b), 'array([1.23400000e+09])')

np.set_printoptions(sign=' ')
assert_equal(repr(a), 'array([ 0., 1., 2., 3.])')
assert_equal(repr(np.array(1.)), 'array( 1.)')
assert_equal(repr(b), 'array([ 1.23400000e+09])')

np.set_printoptions(sign='+')
assert_equal(repr(a), 'array([+0., +1., +2., +3.])')
assert_equal(repr(np.array(1.)), 'array(+1.)')
assert_equal(repr(b), 'array([+1.23400000e+09])')

np.set_printoptions(sign='legacy')
assert_equal(repr(a), 'array([ 0., 1., 2., 3.])')
assert_equal(repr(np.array(1.)), 'array(1.)')
assert_equal(repr(b), 'array([ 1.23400000e+09])')

def test_sign_spacing_structured(self):
a = np.ones(2, dtype='f,f')
Expand Down
0