Skip to content

Commit 5138806

Browse files
authored
Print variable name for cell measures warnings (#350)
1 parent 2b889f4 commit 5138806

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
lines changed

cf_xarray/accessor.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -306,7 +306,12 @@ def _get_measure(obj: DataArray | Dataset, key: str) -> list[str]:
306306
attrs_or_encoding = ChainMap(da.attrs, da.encoding)
307307
if "cell_measures" in attrs_or_encoding:
308308
attr = attrs_or_encoding["cell_measures"]
309-
measures = parse_cell_methods_attr(attr)
309+
try:
310+
measures = parse_cell_methods_attr(attr)
311+
except ValueError as e:
312+
raise ValueError(
313+
f"{var} has malformed cell_measures attribute {attr}."
314+
) from e
310315
if key in measures:
311316
results.update([measures[key]])
312317

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

14811487
keys = {}
14821488
for attr in set(all_attrs):
14831489
try:
14841490
keys.update(parse_cell_methods_attr(attr))
14851491
except ValueError:
1492+
bad_vars = list(
1493+
as_dataset.filter_by_attrs(cell_measures=attr).data_vars.keys()
1494+
)
14861495
warnings.warn(
1487-
f"Ignoring bad cell_measures attribute: {attr}.",
1496+
f"Ignoring bad cell_measures attribute: {attr} on {bad_vars}.",
14881497
UserWarning,
14891498
stacklevel=2,
14901499
)

cf_xarray/tests/test_accessor.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -645,6 +645,8 @@ def test_getitem_errors(obj):
645645
def test_bad_cell_measures_attribute():
646646
air2 = airds.copy(deep=True)
647647
air2.air.attrs["cell_measures"] = "--OPT"
648+
with pytest.warns(UserWarning):
649+
air2.cf["air"]
648650
with pytest.warns(UserWarning):
649651
assert_identical(air2.air.drop_vars("cell_area"), air2.cf["air"])
650652
with pytest.warns(UserWarning):
@@ -659,6 +661,12 @@ def test_bad_cell_measures_attribute():
659661
# GH216
660662
repr(air2.cf)
661663

664+
# GH340
665+
air2.cf.axes
666+
air2.cf.coordinates
667+
with pytest.warns(UserWarning):
668+
air2.cf.cell_measures
669+
662670

663671
def test_getitem_clash_standard_name():
664672
ds = xr.Dataset()

0 commit comments

Comments
 (0)