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

Check for paths in __contains__ #319

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 18 additions & 3 deletions datatree/datatree.py
Original file line number Diff line number Diff line change
Expand Up @@ -616,10 +616,25 @@ def _ipython_key_completions_(self) -> List[str]:
return list(items)

def __contains__(self, key: object) -> bool:
"""The 'in' operator will return true or false depending on whether
'key' is either an array stored in the datatree or a child node, or neither.
"""
return key in self.variables or key in self.children
If key is a string rather (than a path), the 'in' operator will return true or false depending on whether
'key' is either an array stored in the local datatree node, or a child node, or neither.
If key is path-like, the 'in' operator will return true or false depending on whether
'key' is an absolute path to any node in the tree.
"""
if isinstance(key, str):
if "/" in key:
# path-like, so check if this object exists anywhere in the tree
pathkey = NodePath(key)
return pathkey in tuple(
NodePath(node.path) for node in self.root.subtree
)
else:
return key in self.variables or key in self.children
else:
raise TypeError(
f"DataTree objects can't contain objects under non-string keys, but key {key} is of type {type(key)}"
)

def __bool__(self) -> bool:
return bool(self.ds.data_vars) or bool(self.children)
Expand Down
12 changes: 12 additions & 0 deletions datatree/tests/test_datatree.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,18 @@ def test_is_hollow(self):
assert not eve.is_hollow


class TestContains:
def test_contains_key(self):
dat = xr.Dataset({"a": 0})
john = DataTree(name="john", data=dat)
assert "a" in john

def test_contains_path(self):
# https://github.com/xarray-contrib/datatree/issues/240
a = DataTree.from_dict({"a/b/c": None})
assert "/a/b" in a


class TestVariablesChildrenNameCollisions:
def test_parent_already_has_variable_with_childs_name(self):
dt = DataTree(data=xr.Dataset({"a": [0], "b": 1}))
Expand Down
Loading