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

Commit d8e7d38

Browse files
keewisTomNicholas
andauthored
actually allow DataTree objects as values in from_dict (#159)
* allow passing `DataTree` objects as `dict` values * add a test verifying that DataTree objects are actually allowed * ignore mypy error with copied copy method * whatsnew Co-authored-by: Tom Nicholas <[email protected]>
1 parent 0f436e3 commit d8e7d38

File tree

3 files changed

+19
-2
lines changed

3 files changed

+19
-2
lines changed

datatree/datatree.py

+7-2
Original file line numberDiff line numberDiff line change
@@ -754,7 +754,7 @@ def update(self, other: Dataset | Mapping[str, DataTree | DataArray]) -> None:
754754
@classmethod
755755
def from_dict(
756756
cls,
757-
d: MutableMapping[str, Dataset | DataArray | None],
757+
d: MutableMapping[str, Dataset | DataArray | DataTree | None],
758758
name: Optional[str] = None,
759759
) -> DataTree:
760760
"""
@@ -790,7 +790,12 @@ def from_dict(
790790
for path, data in d.items():
791791
# Create and set new node
792792
node_name = NodePath(path).name
793-
new_node = cls(name=node_name, data=data)
793+
if isinstance(data, cls):
794+
# TODO ignoring type error only needed whilst .copy() method is copied from Dataset.copy().
795+
new_node = data.copy() # type: ignore[attr-defined]
796+
new_node.orphan()
797+
else:
798+
new_node = cls(name=node_name, data=data)
794799
obj._set_item(
795800
path,
796801
new_node,

datatree/tests/test_datatree.py

+9
Original file line numberDiff line numberDiff line change
@@ -391,6 +391,15 @@ def test_full(self, simple_datatree):
391391
"/set3",
392392
]
393393

394+
def test_datatree_values(self):
395+
dat1 = DataTree(data=xr.Dataset({"a": 1}))
396+
expected = DataTree()
397+
expected["a"] = dat1
398+
399+
actual = DataTree.from_dict({"a": dat1})
400+
401+
dtt.assert_identical(actual, expected)
402+
394403
def test_roundtrip(self, simple_datatree):
395404
dt = simple_datatree
396405
roundtrip = DataTree.from_dict(dt.to_dict())

docs/source/whats-new.rst

+3
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,9 @@ Deprecations
3737
Bug fixes
3838
~~~~~~~~~
3939

40+
- Allow ``Datatree`` objects as values in :py:meth:`DataTree.from_dict` (:pull:`159`).
41+
By `Justus Magin <https://github.com/keewis>`_.
42+
4043
Documentation
4144
~~~~~~~~~~~~~
4245

0 commit comments

Comments
 (0)