Skip to content

Commit 2eeea4d

Browse files
author
Jim Fulton
authored
chore: Document how tasklets work (#690)
Tasklets are confusing because they rely on special event-loop behavior that was undocumented. Added a comment to work through the example in more detail.
1 parent 926089a commit 2eeea4d

File tree

1 file changed

+25
-2
lines changed

1 file changed

+25
-2
lines changed

packages/google-cloud-ndb/google/cloud/ndb/tasklets.py

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,17 +25,40 @@
2525
the tasklet, any yield of a Future waits for and returns the Future's result.
2626
For example::
2727
28+
from from google.cloud.ndb.tasklets import tasklet
29+
2830
@tasklet
2931
def foo():
30-
a = yield <some Future>
31-
b = yield <another Future>
32+
a = yield <AFuture>
33+
b = yield <BFuture>
3234
return a + b
3335
3436
def main():
3537
f = foo()
3638
x = f.result()
3739
print x
3840
41+
In this example, `foo` needs the results of two futures, `AFuture` and
42+
`BFuture`, which it gets somehow, for example as results of calls.
43+
Rather than waiting for their values and blocking, it yields. First,
44+
the tasklet yields `AFuture`. The event loop gets `AFuture` and takes
45+
care of waiting for its result. When the event loop gets the result
46+
of `AFuture`, it sends it to the tasklet by calling `send` on the
47+
iterator returned by calling the tasklet. The tasklet assigns the
48+
value sent to `a` and then yields `BFuture`. Again the event loop
49+
waits for the result of `BFuture` and sends it to the tasklet. The
50+
tasklet then has what it needs to compute a result.
51+
52+
The tasklet simply returns its result. (Behind the scenes, when you
53+
return a value from a generator in Python 3, a `StopIteration`
54+
exception is raised with the return value as its argument. The event
55+
loop catches the exception and uses the exception argument as the
56+
result of the tasklet. This won't work for Python 2. If you need to
57+
support Python 2, as the library itself does, you'll need to raise a
58+
`google.cloud.ndb.tasklets.Return` exception, with the return value as
59+
the exception argument, as in `google.cloud.ndb.tasklets.Return(a +
60+
b)`.)
61+
3962
Note that blocking until the Future's result is available using result() is
4063
somewhat inefficient (though not vastly -- it is not busy-waiting). In most
4164
cases such code should be rewritten as a tasklet instead::

0 commit comments

Comments
 (0)