Skip to content

Commit 858eba6

Browse files
authored
allow formatting the diff of ndarray attributes (#3728)
* allow comparing with ndarrays * add a test for the attrs diff repr * use array_equiv instead of using all since the comparison may warn
1 parent 47476eb commit 858eba6

File tree

2 files changed

+51
-1
lines changed

2 files changed

+51
-1
lines changed

xarray/core/formatting.py

+12-1
Original file line numberDiff line numberDiff line change
@@ -500,6 +500,13 @@ def diff_dim_summary(a, b):
500500

501501

502502
def _diff_mapping_repr(a_mapping, b_mapping, compat, title, summarizer, col_width=None):
503+
def is_array_like(value):
504+
return (
505+
hasattr(value, "ndim")
506+
and hasattr(value, "shape")
507+
and hasattr(value, "dtype")
508+
)
509+
503510
def extra_items_repr(extra_keys, mapping, ab_side):
504511
extra_repr = [summarizer(k, mapping[k], col_width) for k in extra_keys]
505512
if extra_repr:
@@ -522,7 +529,11 @@ def extra_items_repr(extra_keys, mapping, ab_side):
522529
is_variable = True
523530
except AttributeError:
524531
# compare attribute value
525-
compatible = a_mapping[k] == b_mapping[k]
532+
if is_array_like(a_mapping[k]) or is_array_like(b_mapping[k]):
533+
compatible = array_equiv(a_mapping[k], b_mapping[k])
534+
else:
535+
compatible = a_mapping[k] == b_mapping[k]
536+
526537
is_variable = False
527538

528539
if not compatible:

xarray/tests/test_formatting.py

+39
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
import numpy as np
55
import pandas as pd
6+
import pytest
67

78
import xarray as xr
89
from xarray.core import formatting
@@ -275,6 +276,44 @@ def test_diff_array_repr(self):
275276
except AssertionError:
276277
assert actual == expected.replace(", dtype=int64", "")
277278

279+
@pytest.mark.filterwarnings("error")
280+
def test_diff_attrs_repr_with_array(self):
281+
attrs_a = {"attr": np.array([0, 1])}
282+
283+
attrs_b = {"attr": 1}
284+
expected = dedent(
285+
"""\
286+
Differing attributes:
287+
L attr: [0 1]
288+
R attr: 1
289+
"""
290+
).strip()
291+
actual = formatting.diff_attrs_repr(attrs_a, attrs_b, "equals")
292+
assert expected == actual
293+
294+
attrs_b = {"attr": np.array([-3, 5])}
295+
expected = dedent(
296+
"""\
297+
Differing attributes:
298+
L attr: [0 1]
299+
R attr: [-3 5]
300+
"""
301+
).strip()
302+
actual = formatting.diff_attrs_repr(attrs_a, attrs_b, "equals")
303+
assert expected == actual
304+
305+
# should not raise a warning
306+
attrs_b = {"attr": np.array([0, 1, 2])}
307+
expected = dedent(
308+
"""\
309+
Differing attributes:
310+
L attr: [0 1]
311+
R attr: [0 1 2]
312+
"""
313+
).strip()
314+
actual = formatting.diff_attrs_repr(attrs_a, attrs_b, "equals")
315+
assert expected == actual
316+
278317
def test_diff_dataset_repr(self):
279318
ds_a = xr.Dataset(
280319
data_vars={

0 commit comments

Comments
 (0)