Skip to content
This repository has been archived by the owner on Oct 24, 2024. It is now read-only.

Make illegal path-like variable names when constructing a DataTree from a Dataset #314

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions datatree/datatree.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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)

Expand Down
18 changes: 18 additions & 0 deletions datatree/tests/test_datatree.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import re
from copy import copy, deepcopy

import numpy as np
Expand Down Expand Up @@ -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):
Expand Down
4 changes: 4 additions & 0 deletions docs/source/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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 <https://github.com/etienneschalk>`_.
- Keep attributes on nodes containing no data in :py:func:`map_over_subtree`. (:issue:`278`, :pull:`279`)
By `Sam Levang <https://github.com/slevang>`_.

Expand Down
Loading