From d6b71855c6f9c1ae98913d524f82ffcf1f28318c Mon Sep 17 00:00:00 2001 From: eschalk Date: Sat, 17 Feb 2024 13:05:45 +0100 Subject: [PATCH 1/2] Illegal names --- datatree/datatree.py | 13 +++++++++++++ datatree/tests/test_datatree.py | 18 ++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/datatree/datatree.py b/datatree/datatree.py index c86c2e2e..8d45058e 100644 --- a/datatree/datatree.py +++ b/datatree/datatree.py @@ -103,6 +103,18 @@ def _check_for_name_collisions( ) +def _check_for_slashes_in_names(variables: Iterable[Hashable]) -> None: + offending_variable_names = [ + name for name in variables if isinstance(name, str) and "/" in name + ] + if len(offending_variable_names) > 0: + raise KeyError( + f"Given Dataset contains path-like variable names: {offending_variable_names}. " + "A Dataset represents a group, and a single group " + "cannot have path-like variable names. " + ) + + class DatasetView(Dataset): """ An immutable Dataset-like view onto the data in a single DataTree node. @@ -401,6 +413,7 @@ def __init__( children = {} ds = _coerce_to_dataset(data) _check_for_name_collisions(children, ds.variables) + _check_for_slashes_in_names(ds.variables) super().__init__(name=name) diff --git a/datatree/tests/test_datatree.py b/datatree/tests/test_datatree.py index e9f373d7..59abf5ee 100644 --- a/datatree/tests/test_datatree.py +++ b/datatree/tests/test_datatree.py @@ -1,3 +1,4 @@ +import re from copy import copy, deepcopy import numpy as np @@ -68,6 +69,23 @@ def test_child_gets_named_on_attach(self): mary = DataTree(children={"Sue": sue}) # noqa assert sue.name == "Sue" + def test_dataset_containing_slashes(self): + xda = xr.DataArray( + [[1, 2]], + coords={"label": ["a"], "R30m/y": [30, 60]}, + ) + xds = xr.Dataset({"group/subgroup/my_variable": xda}) + with pytest.raises( + KeyError, + match=re.escape( + "Given Dataset contains path-like variable names: " + "['R30m/y', 'group/subgroup/my_variable']. " + "A Dataset represents a group, and a single group cannot " + "have path-like variable names. " + ), + ): + DataTree(xds) + class TestPaths: def test_path_property(self): From edbb6fde08fd6b2fefc07e4639305b99cb422452 Mon Sep 17 00:00:00 2001 From: eschalk Date: Sat, 17 Feb 2024 13:09:49 +0100 Subject: [PATCH 2/2] Updated whats-new.rst --- docs/source/whats-new.rst | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/source/whats-new.rst b/docs/source/whats-new.rst index 2f6e4f88..4cd75aa7 100644 --- a/docs/source/whats-new.rst +++ b/docs/source/whats-new.rst @@ -45,6 +45,10 @@ Deprecations Bug fixes ~~~~~~~~~ + +- Make illegal path-like variable names when constructing a DataTree from a Dataset + (:issue:`311`, :pull:`314`) + By `Etienne Schalk `_. - Keep attributes on nodes containing no data in :py:func:`map_over_subtree`. (:issue:`278`, :pull:`279`) By `Sam Levang `_.