From 385065b925137264e0507b6cd508594862025384 Mon Sep 17 00:00:00 2001 From: Zackary Loevseth <307867630+ZackaryLoevseth@users.noreply.github.com> Date: Tue, 17 Nov 2026 23:19:10 -0800 Subject: [PATCH] Split blank-separated attribute lists on any whitespace CF allows blank-separated lists to use several spaces between names and to start or end with spaces. Splitting coordinates and ancillary_variables with split(" ") produced empty names. --- cf_xarray/accessor.py | 4 ++-- cf_xarray/tests/test_accessor.py | 25 +++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/cf_xarray/accessor.py b/cf_xarray/accessor.py index 5497cbd7..7beb9d3a 100644 --- a/cf_xarray/accessor.py +++ b/cf_xarray/accessor.py @@ -2303,7 +2303,7 @@ def get_associated_variable_names( # Handles case where the coordinates attribute is None # This is used to tell xarray to not write a coordinates attribute if coordinates := attrs_or_encoding.get("coordinates", None): - coords["coordinates"] = coordinates.split(" ") + coords["coordinates"] = coordinates.split() if "cell_measures" in attrs_or_encoding: try: @@ -2324,7 +2324,7 @@ def get_associated_variable_names( if isinstance(self._obj, Dataset) and ( anc := attrs_or_encoding.get("ancillary_variables", None) ): - coords["ancillary_variables"] = anc.split(" ") + coords["ancillary_variables"] = anc.split() if not skip_bounds: if bounds := attrs_or_encoding.get("bounds", None): diff --git a/cf_xarray/tests/test_accessor.py b/cf_xarray/tests/test_accessor.py index 1214546d..e5e51a59 100644 --- a/cf_xarray/tests/test_accessor.py +++ b/cf_xarray/tests/test_accessor.py @@ -728,6 +728,31 @@ def test_getitem_errors(obj): obj2.cf["X"] +@pytest.mark.parametrize("attribute", ["coordinates", "ancillary_variables"]) +@pytest.mark.parametrize("location", ["attrs", "encoding"]) +@pytest.mark.parametrize( + "names", ["aux1 aux2", "aux1 aux2", " aux1 aux2", "aux1 aux2 ", " aux1 aux2 "] +) +def test_associated_variables_blank_separated(attribute, location, names): + # CF blank-separated lists allow repeated, leading and trailing spaces. + ds = xr.Dataset( + {"data": ("x", [1, 2])}, + coords={"x": [0, 1], "aux1": ("x", [3, 4]), "aux2": ("x", [5, 6])}, + ) + getattr(ds["data"], location)[attribute] = names + original = ds.copy(deep=True) + + with warnings.catch_warnings(): + warnings.simplefilter("error") + associated = ds.cf.get_associated_variable_names("data") + actual = ds.cf["data"] + + assert associated[attribute] == ["aux1", "aux2"] + assert_identical(actual, ds["data"]) + assert_identical(ds, original) + assert getattr(ds["data"], location)[attribute] == names + + def test_bad_cell_measures_attribute() -> None: air2 = airds.copy(deep=False) air2.air.attrs["cell_measures"] = "--OPT"