Skip to content

Commit af8475a

Browse files
added ValueError for missing grid_mapping variable (#458)
* added ValueError for missing grid_mapping variable * added tests for grid_mapping value error
1 parent e283a83 commit af8475a

File tree

2 files changed

+15
-0
lines changed

2 files changed

+15
-0
lines changed

cf_xarray/accessor.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2737,7 +2737,11 @@ def grid_mapping_name(self) -> str:
27372737
if not grid_mapping:
27382738
raise ValueError("No 'grid_mapping' attribute present.")
27392739

2740+
if grid_mapping not in da._coords:
2741+
raise ValueError(f"Grid Mapping variable {grid_mapping} not present.")
2742+
27402743
grid_mapping_var = da[grid_mapping]
2744+
27412745
return grid_mapping_var.attrs["grid_mapping_name"]
27422746

27432747
def __getitem__(self, key: Hashable | Iterable[Hashable]) -> DataArray:

cf_xarray/tests/test_accessor.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1001,6 +1001,17 @@ def test_grid_mappings():
10011001
actual = ds.cf["temp"].cf["rotated_latitude_longitude"]
10021002
assert_identical(actual, expected)
10031003

1004+
# not properly propagated if grid mapping variable not in coords
1005+
with pytest.raises(
1006+
ValueError, match="Grid Mapping variable rotated_pole not present."
1007+
):
1008+
ds.temp.cf.grid_mapping_name
1009+
1010+
# check for https://github.com/xarray-contrib/cf-xarray/issues/448
1011+
expected = ds.rlon
1012+
actual = rotds.temp.cf["X"]
1013+
assert_identical(expected, actual)
1014+
10041015
# Test repr
10051016
expected = """\
10061017
Grid Mappings: rotated_latitude_longitude: ['rotated_pole']"""

0 commit comments

Comments
 (0)