Skip to content

Commit 92ae91c

Browse files
authored
Accounting for NoneType coordinates in attrs/encoding (#359)
1 parent 4748033 commit 92ae91c

File tree

2 files changed

+19
-6
lines changed

2 files changed

+19
-6
lines changed

cf_xarray/accessor.py

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -254,10 +254,12 @@ def _get_axis_coord(obj: DataArray | Dataset, key: str) -> list[str]:
254254
)
255255

256256
search_in = set()
257-
if "coordinates" in obj.encoding:
258-
search_in.update(obj.encoding["coordinates"].split(" "))
259-
if "coordinates" in obj.attrs:
260-
search_in.update(obj.attrs["coordinates"].split(" "))
257+
attrs_or_encoding = ChainMap(obj.attrs, obj.encoding)
258+
coordinates = attrs_or_encoding.get("coordinates", None)
259+
# Handles case where the coordinates attribute is None
260+
# This is used to tell xarray to not write a coordinates attribute
261+
if coordinates:
262+
search_in.update(coordinates.split(" "))
261263
if not search_in:
262264
search_in = set(obj.coords)
263265

@@ -1596,8 +1598,11 @@ def get_associated_variable_names(
15961598
coords: dict[str, list[str]] = {k: [] for k in keys}
15971599
attrs_or_encoding = ChainMap(self._obj[name].attrs, self._obj[name].encoding)
15981600

1599-
if "coordinates" in attrs_or_encoding:
1600-
coords["coordinates"] = attrs_or_encoding["coordinates"].split(" ")
1601+
coordinates = attrs_or_encoding.get("coordinates", None)
1602+
# Handles case where the coordinates attribute is None
1603+
# This is used to tell xarray to not write a coordinates attribute
1604+
if coordinates:
1605+
coords["coordinates"] = coordinates.split(" ")
16011606

16021607
if "cell_measures" in attrs_or_encoding:
16031608
try:

cf_xarray/tests/test_accessor.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -298,6 +298,14 @@ def test_accessor_getattr_and_describe():
298298
assert str(ds_verta.cf) == str(ds_vertb.cf)
299299

300300

301+
def test_accessor_getattr_coordinate_Nonetype():
302+
ds_vert = vert
303+
ds_vert["o3"].encoding["coordinates"] = None
304+
assert ds_vert.o3.cf["latitude"].name == "lat"
305+
ds_vert["lat"].encoding["coordinates"] = None
306+
assert ds_vert.cf["latitude"].name == "lat"
307+
308+
301309
def test_getitem_standard_name():
302310
actual = airds.cf["air_temperature"]
303311
expected = airds["air"]

0 commit comments

Comments
 (0)