Skip to content

Commit b7a5483

Browse files
slevangTomNicholas
andauthored
Keep attrs in map_over_subtree xarray-contrib/datatree#279
* keep attrs in map_over_subtree * more intelligible logic --------- Co-authored-by: Tom Nicholas <[email protected]>
1 parent e72079d commit b7a5483

File tree

3 files changed

+22
-6
lines changed

3 files changed

+22
-6
lines changed

datatree/mapping.py

+9-6
Original file line numberDiff line numberDiff line change
@@ -206,14 +206,17 @@ def _map_over_subtree(*args, **kwargs) -> DataTree | Tuple[DataTree, ...]:
206206
node_of_first_tree.path
207207
)(func)
208208

209-
# Now we can call func on the data in this particular set of corresponding nodes
210-
results = (
211-
func_with_error_context(
209+
if node_of_first_tree.has_data:
210+
# call func on the data in this particular set of corresponding nodes
211+
results = func_with_error_context(
212212
*node_args_as_datasetviews, **node_kwargs_as_datasetviews
213213
)
214-
if node_of_first_tree.has_data
215-
else None
216-
)
214+
elif node_of_first_tree.has_attrs:
215+
# propagate attrs
216+
results = node_of_first_tree.ds
217+
else:
218+
# nothing to propagate so use fastpath to create empty node in new tree
219+
results = None
217220

218221
# TODO implement mapping over multiple trees in-place using if conditions from here on?
219222
out_data_objects[node_of_first_tree.path] = results

datatree/tests/test_mapping.py

+11
Original file line numberDiff line numberDiff line change
@@ -264,6 +264,17 @@ def check_for_data(ds):
264264

265265
dt.map_over_subtree(check_for_data)
266266

267+
def test_keep_attrs_on_empty_nodes(self, create_test_datatree):
268+
# GH278
269+
dt = create_test_datatree()
270+
dt["set1/set2"].attrs["foo"] = "bar"
271+
272+
def empty_func(ds):
273+
return ds
274+
275+
result = dt.map_over_subtree(empty_func)
276+
assert result["set1/set2"].attrs == dt["set1/set2"].attrs
277+
267278
@pytest.mark.xfail(
268279
reason="probably some bug in pytests handling of exception notes"
269280
)

docs/source/whats-new.rst

+2
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,8 @@ Deprecations
3535

3636
Bug fixes
3737
~~~~~~~~~
38+
- Keep attributes on nodes containing no data in :py:func:`map_over_subtree`. (:issue:`278`, :pull:`279`)
39+
By `Sam Levang <https://github.com/slevang>`_.
3840

3941
Documentation
4042
~~~~~~~~~~~~~

0 commit comments

Comments
 (0)