Added optional "condition" argument to "get_parent" traversing helper function
authorThierry Florac <thierry.florac@onf.fr>
Tue, 11 Oct 2016 16:21:25 +0200
changeset 67 8b172808ca6c
parent 66 1e9c6d17203e
child 68 7f90df24ceca
Added optional "condition" argument to "get_parent" traversing helper function
src/pyams_utils/traversing.py
--- a/src/pyams_utils/traversing.py	Thu Jun 02 16:41:14 2016 +0200
+++ b/src/pyams_utils/traversing.py	Tue Oct 11 16:21:25 2016 +0200
@@ -167,15 +167,25 @@
                 'root': root}
 
 
-def get_parent(context, interface=Interface, allow_context=True):
-    """Get first parent of the context that implements given interface"""
+def get_parent(context, interface=Interface, allow_context=True, condition=None):
+    """Get first parent of the context that implements given interface
+
+    @context: base element
+    @interface: the interface that parend should implement
+    @allow_context: if 'True' (the default), traversing is done starting with context; otherwise,
+        traversing is done starting from context's parent
+    @condition: an optional function that should return a 'True' result when called with parent
+        as first argument
+    """
     if allow_context:
         parent = context
     else:
         parent = getattr(context, '__parent__', None)
     while parent is not None:
         if interface.providedBy(parent):
-            return interface(parent)
+            target = interface(parent)
+            if (not condition) or condition(target):
+                return target
         parent = getattr(parent, '__parent__', None)
     return None