Skip to content

Commit 5a0e07b

Browse files
authored
copy subtrees without creating nodes for ancestors xarray-contrib/datatree#201
* use relative paths for the copied descendants * check that copying subtrees works * changelog
1 parent cfd2a54 commit 5a0e07b

File tree

3 files changed

+12
-1
lines changed

3 files changed

+12
-1
lines changed

datatree/datatree.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -734,7 +734,8 @@ def _copy_subtree(
734734
"""Copy entire subtree"""
735735
new_tree = self._copy_node(deep=deep)
736736
for node in self.descendants:
737-
new_tree[node.path] = node._copy_node(deep=deep)
737+
path = node.relative_to(self)
738+
new_tree[path] = node._copy_node(deep=deep)
738739
return new_tree
739740

740741
def _copy_node(

datatree/tests/test_datatree.py

+8
Original file line numberDiff line numberDiff line change
@@ -263,6 +263,14 @@ def test_copy(self, create_test_datatree):
263263
assert "foo" not in node.attrs
264264
assert node.attrs["Test"] is copied_node.attrs["Test"]
265265

266+
def test_copy_subtree(self):
267+
dt = DataTree.from_dict({"/level1/level2/level3": xr.Dataset()})
268+
269+
actual = dt["/level1/level2"].copy()
270+
expected = DataTree.from_dict({"/level3": xr.Dataset()}, name="level2")
271+
272+
dtt.assert_identical(actual, expected)
273+
266274
def test_deepcopy(self, create_test_datatree):
267275
dt = create_test_datatree()
268276

docs/source/whats-new.rst

+2
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,8 @@ Bug fixes
4242

4343
- Allow for altering of given dataset inside function called by :py:func:`map_over_subtree` (:issue:`188`, :pull:`194`).
4444
By `Tom Nicholas <https://github.com/TomNicholas>`_.
45+
- copy subtrees without creating ancestor nodes (:pull:`201`)
46+
By `Justus Magin <https://github.com/keewis>`_.
4547

4648
Documentation
4749
~~~~~~~~~~~~~

0 commit comments

Comments
 (0)