Added "find_objects_..." functions (based on ISubLocations interface)
authorThierry Florac <thierry.florac@onf.fr>
Mon, 11 Apr 2016 17:37:23 +0200
changeset 56 01de65ad00fb
parent 55 d20591346980
child 57 c7f27ae4230d
Added "find_objects_..." functions (based on ISubLocations interface)
src/pyams_utils/container.py
--- a/src/pyams_utils/container.py	Fri Jan 29 15:39:09 2016 +0100
+++ b/src/pyams_utils/container.py	Mon Apr 11 17:37:23 2016 +0200
@@ -52,3 +52,31 @@
         if IContainer.providedBy(context):
             for key in context:
                 yield context[key]
+
+
+def find_objects_matching(root, condition, ignore_root=False):
+    """Find all objects in root that match the condition
+
+    The condition is a Python callable object that takes an object as
+    argument and must return a boolean result.
+
+    All sub-objects of the root will also be searched recursively.
+    """
+    if (not ignore_root) and condition(root):
+        yield root
+    locations = ISublocations(root, None)
+    if locations is not None:
+        for location in locations.sublocations():
+            if condition(location):
+                yield location
+            for sublocation in find_objects_matching(location, condition, ignore_root=True):
+                yield sublocation
+
+
+def find_objects_providing(root, interface):
+    """Find all objects in root that provide the specified interface
+
+    All sub-objects of the root will also be searched recursively.
+    """
+    for match in find_objects_matching(root, interface.providedBy):
+        yield match