Skip to content

Commit

Permalink
Print variable name for cell measures warnings (#350)
Browse files Browse the repository at this point in the history
  • Loading branch information
dcherian authored Jul 15, 2022
1 parent 2b889f4 commit 5138806
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
13 changes: 11 additions & 2 deletions cf_xarray/accessor.py
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,12 @@ def _get_measure(obj: DataArray | Dataset, key: str) -> list[str]:
attrs_or_encoding = ChainMap(da.attrs, da.encoding)
if "cell_measures" in attrs_or_encoding:
attr = attrs_or_encoding["cell_measures"]
measures = parse_cell_methods_attr(attr)
try:
measures = parse_cell_methods_attr(attr)
except ValueError as e:
raise ValueError(
f"{var} has malformed cell_measures attribute {attr}."
) from e
if key in measures:
results.update([measures[key]])

Expand Down Expand Up @@ -1477,14 +1482,18 @@ def cell_measures(self) -> dict[str, list[str]]:
ChainMap(da.attrs, da.encoding).get("cell_measures", "")
for da in obj.data_vars.values()
]
as_dataset = self._maybe_to_dataset().reset_coords()

keys = {}
for attr in set(all_attrs):
try:
keys.update(parse_cell_methods_attr(attr))
except ValueError:
bad_vars = list(
as_dataset.filter_by_attrs(cell_measures=attr).data_vars.keys()
)
warnings.warn(
f"Ignoring bad cell_measures attribute: {attr}.",
f"Ignoring bad cell_measures attribute: {attr} on {bad_vars}.",
UserWarning,
stacklevel=2,
)
Expand Down
8 changes: 8 additions & 0 deletions cf_xarray/tests/test_accessor.py
Original file line number Diff line number Diff line change
Expand Up @@ -645,6 +645,8 @@ def test_getitem_errors(obj):
def test_bad_cell_measures_attribute():
air2 = airds.copy(deep=True)
air2.air.attrs["cell_measures"] = "--OPT"
with pytest.warns(UserWarning):
air2.cf["air"]
with pytest.warns(UserWarning):
assert_identical(air2.air.drop_vars("cell_area"), air2.cf["air"])
with pytest.warns(UserWarning):
Expand All @@ -659,6 +661,12 @@ def test_bad_cell_measures_attribute():
# GH216
repr(air2.cf)

# GH340
air2.cf.axes
air2.cf.coordinates
with pytest.warns(UserWarning):
air2.cf.cell_measures


def test_getitem_clash_standard_name():
ds = xr.Dataset()
Expand Down

0 comments on commit 5138806

Please sign in to comment.