From 858eba6f1a99b4b1e37ab16f76d4bd060c5598fb Mon Sep 17 00:00:00 2001 From: keewis Date: Sun, 23 Feb 2020 20:13:45 +0100 Subject: [PATCH] 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 --- xarray/core/formatting.py | 13 ++++++++++- xarray/tests/test_formatting.py | 39 +++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 1 deletion(-) diff --git a/xarray/core/formatting.py b/xarray/core/formatting.py index 520fa9b9f1b..89246ff228d 100644 --- a/xarray/core/formatting.py +++ b/xarray/core/formatting.py @@ -500,6 +500,13 @@ def diff_dim_summary(a, b): def _diff_mapping_repr(a_mapping, b_mapping, compat, title, summarizer, col_width=None): + def is_array_like(value): + return ( + hasattr(value, "ndim") + and hasattr(value, "shape") + and hasattr(value, "dtype") + ) + def extra_items_repr(extra_keys, mapping, ab_side): extra_repr = [summarizer(k, mapping[k], col_width) for k in extra_keys] if extra_repr: @@ -522,7 +529,11 @@ def extra_items_repr(extra_keys, mapping, ab_side): is_variable = True except AttributeError: # compare attribute value - compatible = a_mapping[k] == b_mapping[k] + if is_array_like(a_mapping[k]) or is_array_like(b_mapping[k]): + compatible = array_equiv(a_mapping[k], b_mapping[k]) + else: + compatible = a_mapping[k] == b_mapping[k] + is_variable = False if not compatible: diff --git a/xarray/tests/test_formatting.py b/xarray/tests/test_formatting.py index 9a1f0bbd975..61ecf46b79b 100644 --- a/xarray/tests/test_formatting.py +++ b/xarray/tests/test_formatting.py @@ -3,6 +3,7 @@ import numpy as np import pandas as pd +import pytest import xarray as xr from xarray.core import formatting @@ -275,6 +276,44 @@ def test_diff_array_repr(self): except AssertionError: assert actual == expected.replace(", dtype=int64", "") + @pytest.mark.filterwarnings("error") + def test_diff_attrs_repr_with_array(self): + attrs_a = {"attr": np.array([0, 1])} + + attrs_b = {"attr": 1} + expected = dedent( + """\ + Differing attributes: + L attr: [0 1] + R attr: 1 + """ + ).strip() + actual = formatting.diff_attrs_repr(attrs_a, attrs_b, "equals") + assert expected == actual + + attrs_b = {"attr": np.array([-3, 5])} + expected = dedent( + """\ + Differing attributes: + L attr: [0 1] + R attr: [-3 5] + """ + ).strip() + actual = formatting.diff_attrs_repr(attrs_a, attrs_b, "equals") + assert expected == actual + + # should not raise a warning + attrs_b = {"attr": np.array([0, 1, 2])} + expected = dedent( + """\ + Differing attributes: + L attr: [0 1] + R attr: [0 1 2] + """ + ).strip() + actual = formatting.diff_attrs_repr(attrs_a, attrs_b, "equals") + assert expected == actual + def test_diff_dataset_repr(self): ds_a = xr.Dataset( data_vars={