Skip to content

Commit

Permalink
allow formatting the diff of ndarray attributes (#3728)
Browse files Browse the repository at this point in the history
* allow comparing with ndarrays

* add a test for the attrs diff repr

* use array_equiv instead of using all since the comparison may warn
  • Loading branch information
keewis authored Feb 23, 2020
1 parent 47476eb commit 858eba6
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
13 changes: 12 additions & 1 deletion xarray/core/formatting.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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:
Expand Down
39 changes: 39 additions & 0 deletions xarray/tests/test_formatting.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

import numpy as np
import pandas as pd
import pytest

import xarray as xr
from xarray.core import formatting
Expand Down Expand Up @@ -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={
Expand Down

0 comments on commit 858eba6

Please sign in to comment.