Skip to content

Commit

Permalink
make .parent read-only, and remove tests which test the parent setter
Browse files Browse the repository at this point in the history
  • Loading branch information
TomNicholas committed Sep 7, 2024
1 parent 7ce6b56 commit 897b589
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 20 deletions.
8 changes: 1 addition & 7 deletions xarray/core/datatree.py
Original file line number Diff line number Diff line change
Expand Up @@ -500,12 +500,6 @@ def parent(self: DataTree) -> DataTree | None:
"""Parent of this node."""
return self._parent

@parent.setter
def parent(self: DataTree, new_parent: DataTree) -> None:
if new_parent and self.name is None:
raise ValueError("Cannot set an unnamed node as a child of another node")
self._set_parent(new_parent, self.name)

def _to_dataset_view(self, rebuild_dims: bool) -> DatasetView:
variables = dict(self._data_variables)
variables |= self._coord_variables
Expand Down Expand Up @@ -894,7 +888,7 @@ def _set(self, key: str, val: DataTree | CoercibleValue) -> None:
# create and assign a shallow copy here so as not to alter original name of node in grafted tree
new_node = val.copy(deep=False)
new_node.name = key
new_node.parent = self
new_node._set_parent(new_parent=self, child_name=key)
else:
if not isinstance(val, DataArray | Variable):
# accommodate other types that can be coerced into Variables
Expand Down
6 changes: 6 additions & 0 deletions xarray/core/treenode.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,12 @@ def parent(self) -> Tree | None:
"""Parent of this node."""
return self._parent

@parent.setter
def parent(self: Tree, new_parent: Tree) -> None:
raise AttributeError(
"Cannot set parent attribute directly, you must modify the children attribute of the other node instead"
)

def _set_parent(
self, new_parent: Tree | None, child_name: str | None = None
) -> None:
Expand Down
13 changes: 0 additions & 13 deletions xarray/tests/test_datatree.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,25 +35,12 @@ def test_bad_names(self):


class TestFamilyTree:
def test_dont_modify_parent_inplace(self):
# GH issue 9196
root: DataTree = DataTree(name="root")
child: DataTree = DataTree(name="child")
child.parent = root
assert root.children == {}

def test_dont_modify_children_inplace(self):
# GH issue 9196
child: DataTree = DataTree()
DataTree(children={"child": child})
assert child.parent is None

def test_setparent_unnamed_child_node_fails(self):
john: DataTree = DataTree(name="john")
with pytest.raises(ValueError, match="unnamed"):
child = DataTree(name=None)
child.parent = john

def test_create_two_children(self):
root_data = xr.Dataset({"a": ("y", [6, 7, 8]), "set0": ("x", [9, 10])})
set1_data = xr.Dataset({"a": 0, "b": 1})
Expand Down

0 comments on commit 897b589

Please sign in to comment.