Skip to content

Commit 88eb8ca

Browse files
authored
Add documentation for find/findall using visit (#1241)
* Add documentation for find/findall using visit * Remove whitespace * Fix print result * Fix indentation issue in the docstring * Indent literal block
1 parent 8e6fe11 commit 88eb8ca

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

zarr/hierarchy.py

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -720,6 +720,76 @@ def visit(self, func):
720720
baz
721721
quux
722722
723+
Search for members matching some name query can be implemented using
724+
``visit`` that is, ``find`` and ``findall``. Consider the following
725+
tree::
726+
727+
/
728+
├── aaa
729+
│ └── bbb
730+
│ └── ccc
731+
│ └── aaa
732+
├── bar
733+
└── foo
734+
735+
It is created as follows:
736+
737+
>>> root = zarr.group()
738+
>>> foo = root.create_group("foo")
739+
>>> bar = root.create_group("bar")
740+
>>> root.create_group("aaa").create_group("bbb").create_group("ccc").create_group("aaa")
741+
<zarr.hierarchy.Group '/aaa/bbb/ccc/aaa'>
742+
743+
For ``find``, the first path that matches a given pattern (for example
744+
"aaa") is returned. Note that a non-None value is returned in the visit
745+
function to stop further iteration.
746+
747+
>>> import re
748+
>>> pattern = re.compile("aaa")
749+
>>> found = None
750+
>>> def find(path):
751+
... global found
752+
... if pattern.search(path) is not None:
753+
... found = path
754+
... return True
755+
...
756+
>>> root.visit(find)
757+
True
758+
>>> print(found)
759+
aaa
760+
761+
For ``findall``, all the results are gathered into a list
762+
763+
>>> pattern = re.compile("aaa")
764+
>>> found = []
765+
>>> def findall(path):
766+
... if pattern.search(path) is not None:
767+
... found.append(path)
768+
...
769+
>>> root.visit(findall)
770+
>>> print(found)
771+
['aaa', 'aaa/bbb', 'aaa/bbb/ccc', 'aaa/bbb/ccc/aaa']
772+
773+
To match only on the last part of the path, use a greedy regex to filter
774+
out the prefix:
775+
776+
>>> prefix_pattern = re.compile(r".*/")
777+
>>> pattern = re.compile("aaa")
778+
>>> found = []
779+
>>> def findall(path):
780+
... match = prefix_pattern.match(path)
781+
... if match is None:
782+
... name = path
783+
... else:
784+
... _, end = match.span()
785+
... name = path[end:]
786+
... if pattern.search(name) is not None:
787+
... found.append(path)
788+
... return None
789+
...
790+
>>> root.visit(findall)
791+
>>> print(found)
792+
['aaa', 'aaa/bbb/ccc/aaa']
723793
"""
724794

725795
base_len = len(self.name)

0 commit comments

Comments
 (0)