Skip to content

Commit 03583e4

Browse files
authored
Fix get_bounds_dim_name regression. (#473)
Handle the case where `lat` and `lat_bounds` have same attributes. Closes #442
1 parent c4d662e commit 03583e4

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

cf_xarray/accessor.py

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2296,8 +2296,20 @@ def get_bounds_dim_name(self, key: Hashable) -> Hashable:
22962296
-------
22972297
str
22982298
"""
2299-
(crd_name,) = apply_mapper(_get_all, self._obj, key, error=False, default=[key])
2299+
# In many cases, the bounds variable has the same attrs as the coordinate variable
2300+
# So multiple matches are possible.
2301+
crd_names = apply_mapper(_get_all, self._obj, key, error=False, default=[key])
2302+
23002303
variables = self._obj._variables
2304+
filtered = [
2305+
crd_name for crd_name in crd_names if "bounds" in variables[crd_name].attrs
2306+
]
2307+
if len(filtered) > 1:
2308+
raise KeyError(
2309+
f"Received multiple matches for {key!r} that have a bounds attribute: {filtered!r} "
2310+
)
2311+
2312+
(crd_name,) = filtered
23012313
crd = variables[crd_name]
23022314
crd_attrs = crd._attrs
23032315
if crd_attrs is None or "bounds" not in crd_attrs:

cf_xarray/tests/test_accessor.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -974,6 +974,14 @@ def test_get_bounds_dim_name() -> None:
974974
assert mollwds.cf.get_bounds_dim_name("longitude") == "bounds"
975975
assert mollwds.cf.get_bounds_dim_name("lon") == "bounds"
976976

977+
# Be OK with bounds and coordinates having same attributes
978+
# GH442
979+
assert vert.cf.get_bounds_dim_name("longitude") == "bnds"
980+
ds = vert.copy(deep=True)
981+
ds.lat.attrs["standard_name"] = "longitude"
982+
with pytest.raises(KeyError):
983+
ds.cf.get_bounds_dim_name("longitude")
984+
977985

978986
def test_grid_mappings():
979987
ds = rotds.copy(deep=False)

0 commit comments

Comments
 (0)