Skip to content

Commit c8251e3

Browse files
dnowacki-usgsmax-sixty
authored andcommitted
Partial fix for #2841 to improve formatting. (#2906)
Updates formatting to use .format() instead of % operator. Changed all instances of % to .format() and added test for using tuple as key, which errored using % operator. pep8 Remove positional indexes and fix !r formatting bug
1 parent f8ae987 commit c8251e3

File tree

2 files changed

+34
-20
lines changed

2 files changed

+34
-20
lines changed

xarray/core/formatting.py

Lines changed: 23 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ def format_timestamp(t):
116116
if time_str == '00:00:00':
117117
return date_str
118118
else:
119-
return '%sT%s' % (date_str, time_str)
119+
return '{}T{}'.format(date_str, time_str)
120120

121121

122122
def format_timedelta(t, timedelta_format=None):
@@ -212,12 +212,12 @@ def summarize_variable(name, var, col_width, show_values=True,
212212
marker=' ', max_width=None):
213213
if max_width is None:
214214
max_width = OPTIONS['display_width']
215-
first_col = pretty_print(' %s %s ' % (marker, name), col_width)
215+
first_col = pretty_print(' {} {} '.format(marker, name), col_width)
216216
if var.dims:
217-
dims_str = '(%s) ' % ', '.join(map(str, var.dims))
217+
dims_str = '({}) '.format(', '.join(map(str, var.dims)))
218218
else:
219219
dims_str = ''
220-
front_str = '%s%s%s ' % (first_col, dims_str, var.dtype)
220+
front_str = '{}{}{} '.format(first_col, dims_str, var.dtype)
221221
if show_values:
222222
values_str = format_array_flat(var, max_width - len(front_str))
223223
elif isinstance(var._data, dask_array_type):
@@ -229,8 +229,9 @@ def summarize_variable(name, var, col_width, show_values=True,
229229

230230

231231
def _summarize_coord_multiindex(coord, col_width, marker):
232-
first_col = pretty_print(' %s %s ' % (marker, coord.name), col_width)
233-
return '%s(%s) MultiIndex' % (first_col, str(coord.dims[0]))
232+
first_col = pretty_print(' {} {} '.format(
233+
marker, coord.name), col_width)
234+
return '{}({}) MultiIndex'.format(first_col, str(coord.dims[0]))
234235

235236

236237
def _summarize_coord_levels(coord, col_width, marker='-'):
@@ -264,13 +265,14 @@ def summarize_coord(name, var, col_width):
264265
def summarize_attr(key, value, col_width=None):
265266
"""Summary for __repr__ - use ``X.attrs[key]`` for full value."""
266267
# Indent key and add ':', then right-pad if col_width is not None
267-
k_str = ' %s:' % key
268+
k_str = ' {}:'.format(key)
268269
if col_width is not None:
269270
k_str = pretty_print(k_str, col_width)
270271
# Replace tabs and newlines, so we print on one line in known width
271272
v_str = str(value).replace('\t', '\\t').replace('\n', '\\n')
272273
# Finally, truncate to the desired display width
273-
return maybe_truncate('%s %s' % (k_str, v_str), OPTIONS['display_width'])
274+
return maybe_truncate('{} {}'.format(k_str, v_str),
275+
OPTIONS['display_width'])
274276

275277

276278
EMPTY_REPR = ' *empty*'
@@ -303,7 +305,7 @@ def _calculate_col_width(col_items):
303305
def _mapping_repr(mapping, title, summarizer, col_width=None):
304306
if col_width is None:
305307
col_width = _calculate_col_width(mapping)
306-
summary = ['%s:' % title]
308+
summary = ['{}:'.format(title)]
307309
if mapping:
308310
summary += [summarizer(k, v, col_width) for k, v in mapping.items()]
309311
else:
@@ -329,19 +331,19 @@ def coords_repr(coords, col_width=None):
329331
def indexes_repr(indexes):
330332
summary = []
331333
for k, v in indexes.items():
332-
summary.append(wrap_indent(repr(v), '%s: ' % k))
334+
summary.append(wrap_indent(repr(v), '{}: '.format(k)))
333335
return '\n'.join(summary)
334336

335337

336338
def dim_summary(obj):
337-
elements = ['%s: %s' % (k, v) for k, v in obj.sizes.items()]
339+
elements = ['{}: {}'.format(k, v) for k, v in obj.sizes.items()]
338340
return ', '.join(elements)
339341

340342

341343
def unindexed_dims_repr(dims, coords):
342344
unindexed_dims = [d for d in dims if d not in coords]
343345
if unindexed_dims:
344-
dims_str = ', '.join('%s' % d for d in unindexed_dims)
346+
dims_str = ', '.join('{}'.format(d) for d in unindexed_dims)
345347
return 'Dimensions without coordinates: ' + dims_str
346348
else:
347349
return None
@@ -382,10 +384,11 @@ def short_dask_repr(array, show_dtype=True):
382384
"""
383385
chunksize = tuple(c[0] for c in array.chunks)
384386
if show_dtype:
385-
return 'dask.array<shape=%s, dtype=%s, chunksize=%s>' % (
387+
return 'dask.array<shape={}, dtype={}, chunksize={}>'.format(
386388
array.shape, array.dtype, chunksize)
387389
else:
388-
return 'dask.array<shape=%s, chunksize=%s>' % (array.shape, chunksize)
390+
return 'dask.array<shape={}, chunksize={}>'.format(
391+
array.shape, chunksize)
389392

390393

391394
def short_data_repr(array):
@@ -394,18 +397,18 @@ def short_data_repr(array):
394397
elif array._in_memory or array.size < 1e5:
395398
return short_array_repr(array.values)
396399
else:
397-
return u'[%s values with dtype=%s]' % (array.size, array.dtype)
400+
return u'[{} values with dtype={}]'.format(array.size, array.dtype)
398401

399402

400403
def array_repr(arr):
401404
# used for DataArray, Variable and IndexVariable
402405
if hasattr(arr, 'name') and arr.name is not None:
403-
name_str = '%r ' % arr.name
406+
name_str = '{!r} '.format(arr.name)
404407
else:
405408
name_str = ''
406409

407-
summary = ['<xarray.%s %s(%s)>'
408-
% (type(arr).__name__, name_str, dim_summary(arr))]
410+
summary = ['<xarray.{} {}({})>'.format(
411+
type(arr).__name__, name_str, dim_summary(arr))]
409412

410413
summary.append(short_data_repr(arr))
411414

@@ -424,12 +427,12 @@ def array_repr(arr):
424427

425428

426429
def dataset_repr(ds):
427-
summary = ['<xarray.%s>' % type(ds).__name__]
430+
summary = ['<xarray.{}>'.format(type(ds).__name__)]
428431

429432
col_width = _calculate_col_width(_get_col_items(ds.variables))
430433

431434
dims_start = pretty_print('Dimensions:', col_width)
432-
summary.append('%s(%s)' % (dims_start, dim_summary(ds)))
435+
summary.append('{}({})'.format(dims_start, dim_summary(ds)))
433436

434437
if ds.coords:
435438
summary.append(coords_repr(ds.coords, col_width=col_width))

xarray/tests/test_formatting.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -303,6 +303,17 @@ def test_diff_dataset_repr(self):
303303
actual = formatting.diff_dataset_repr(ds_a, ds_b, 'identical')
304304
assert actual == expected
305305

306+
def test_array_repr(self):
307+
ds = xr.Dataset(coords={'foo': [1, 2, 3], 'bar': [1, 2, 3]})
308+
ds[(1, 2)] = xr.DataArray([0], dims='test')
309+
actual = formatting.array_repr(ds[(1, 2)])
310+
expected = dedent("""\
311+
<xarray.DataArray (1, 2) (test: 1)>
312+
array([0])
313+
Dimensions without coordinates: test""")
314+
315+
assert actual == expected
316+
306317

307318
def test_set_numpy_options():
308319
original_options = np.get_printoptions()

0 commit comments

Comments
 (0)