Skip to content

Commit

Permalink
Name checking (#106)
Browse files Browse the repository at this point in the history
* test for invalid node names

* check for invalid node names in property setter

* remove typing confusion

* whatsnew
  • Loading branch information
TomNicholas authored Jun 3, 2022
1 parent 432981f commit 34116c2
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 2 deletions.
9 changes: 7 additions & 2 deletions datatree/datatree.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ class DataTree(

def __init__(
self,
data: Optional[Dataset | DataArray] = None,
data: Dataset | DataArray = None,
parent: DataTree = None,
children: Mapping[str, DataTree] = None,
name: str = None,
Expand Down Expand Up @@ -119,7 +119,7 @@ def __init__(
super().__init__(children=children)
self.name = name
self.parent = parent
self.ds = data # type: ignore[assignment]
self.ds = data

@property
def name(self) -> str | None:
Expand All @@ -128,6 +128,11 @@ def name(self) -> str | None:

@name.setter
def name(self, name: str | None) -> None:
if name is not None:
if not isinstance(name, str):
raise TypeError("node name must be a string or None")
if "/" in name:
raise ValueError("node names cannot contain forward slashes")
self._name = name

@property
Expand Down
7 changes: 7 additions & 0 deletions datatree/tests/test_datatree.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,13 @@ def test_unnamed(self):
dt = DataTree()
assert dt.name is None

def test_bad_names(self):
with pytest.raises(TypeError):
DataTree(name=5)

with pytest.raises(ValueError):
DataTree(name="folder/data")


class TestFamilyTree:
def test_setparent_unnamed_child_node_fails(self):
Expand Down
2 changes: 2 additions & 0 deletions docs/source/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ Bug fixes
By `Matt McCormick <https://github.com/thewtex>`_.
- Fix netCDF encoding for compression (:pull:`95`)
By `Joe Hamman <https://github.com/jhamman>`_.
- Added validity checking for node names (:pull:`106`)
By `Tom Nicholas <https://github.com/TomNicholas>`_.

Documentation
~~~~~~~~~~~~~
Expand Down

0 comments on commit 34116c2

Please sign in to comment.