changeset 998:42eb1cf66ac1

New deep_wait function. This function (it is really a class which acts like a function) takes a value as input and gives a Deferred back. The promise is that the Deferred will only trigger when all Deferreds in the value have been triggered themselves. This happens recursively, meaning that deep_wait will keep waiting until the value if fully evaluated.
author Martin Geisler <mg@daimi.au.dk>
date Tue, 14 Oct 2008 15:06:42 +0200
parents 4a31eebed787
children 23a883d5a4b3
files viff/util.py
diffstat 1 files changed, 25 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/viff/util.py	Tue Oct 14 15:05:37 2008 +0200
+++ b/viff/util.py	Tue Oct 14 15:06:42 2008 +0200
@@ -195,6 +195,31 @@
     return clone
 
 
+class deep_wait(Deferred):
+
+    def __init__(self, result):
+        Deferred.__init__(self)
+        self._wait(result)
+
+    def _wait(self, value):
+        deferreds = []
+
+        def collect(value):
+            if isinstance(value, Deferred):
+                deferreds.append(value)
+            if isinstance(value, (tuple, list)):
+                map(collect, value)
+
+        collect(value)
+
+        if deferreds:
+            # There are one or more Deferreds to wait on.
+            gatherResults(deferreds).addCallback(self._wait)
+        else:
+            # Found no Deferreds -- there is nothing to wait on and so
+            # we are done!
+            self.callback(None)
+
 def find_prime(lower_bound, blum=False):
     """Find a prime above a lower bound.