Skip to content

Commit

Permalink
Fix get_bounds_dim_name regression. (#473)
Browse files Browse the repository at this point in the history
Handle the case where `lat` and `lat_bounds` have same attributes.

Closes #442
  • Loading branch information
dcherian authored Oct 24, 2023
1 parent c4d662e commit 03583e4
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
14 changes: 13 additions & 1 deletion cf_xarray/accessor.py
Original file line number Diff line number Diff line change
Expand Up @@ -2296,8 +2296,20 @@ def get_bounds_dim_name(self, key: Hashable) -> Hashable:
-------
str
"""
(crd_name,) = apply_mapper(_get_all, self._obj, key, error=False, default=[key])
# In many cases, the bounds variable has the same attrs as the coordinate variable
# So multiple matches are possible.
crd_names = apply_mapper(_get_all, self._obj, key, error=False, default=[key])

variables = self._obj._variables
filtered = [
crd_name for crd_name in crd_names if "bounds" in variables[crd_name].attrs
]
if len(filtered) > 1:
raise KeyError(
f"Received multiple matches for {key!r} that have a bounds attribute: {filtered!r} "
)

(crd_name,) = filtered
crd = variables[crd_name]
crd_attrs = crd._attrs
if crd_attrs is None or "bounds" not in crd_attrs:
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 @@ -974,6 +974,14 @@ def test_get_bounds_dim_name() -> None:
assert mollwds.cf.get_bounds_dim_name("longitude") == "bounds"
assert mollwds.cf.get_bounds_dim_name("lon") == "bounds"

# Be OK with bounds and coordinates having same attributes
# GH442
assert vert.cf.get_bounds_dim_name("longitude") == "bnds"
ds = vert.copy(deep=True)
ds.lat.attrs["standard_name"] = "longitude"
with pytest.raises(KeyError):
ds.cf.get_bounds_dim_name("longitude")


def test_grid_mappings():
ds = rotds.copy(deep=False)
Expand Down

0 comments on commit 03583e4

Please sign in to comment.