[Python-checkins] cpython: asyncio doc: add an example with Future

victor.stinner python-checkins at python.org
Mon Dec 9 12:40:39 CET 2013


http://hg.python.org/cpython/rev/40e8485530bc
changeset:   87850:40e8485530bc
user:        Victor Stinner <victor.stinner at gmail.com>
date:        Mon Dec 09 12:40:17 2013 +0100
summary:
  asyncio doc: add an example with Future

files:
  Doc/library/asyncio-task.rst |  24 ++++++++++++++++++++++++
  1 files changed, 24 insertions(+), 0 deletions(-)


diff --git a/Doc/library/asyncio-task.rst b/Doc/library/asyncio-task.rst
--- a/Doc/library/asyncio-task.rst
+++ b/Doc/library/asyncio-task.rst
@@ -408,3 +408,27 @@
 
 * ``wait_task()`` stops the event loop when ``print_sum()`` is done.
 
+
+Example: Future and get result
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Example combining a :class:`Future` and a :ref:`coroutine <coroutine>`::
+
+    import asyncio
+
+    @asyncio.coroutine
+    def slow_operation(future):
+        yield from asyncio.sleep(1)
+        future.set_result('Future in done!')
+
+    loop = asyncio.get_event_loop()
+    future = asyncio.Future()
+    asyncio.Task(slow_operation(future))
+    loop.run_until_complete(future)
+    print(future.result())
+    loop.close()
+
+The example waits for the completion of the future (which takes 1 second). The
+coroutine is responsible of the computation. The event loop is notified when
+the future is done (see the :meth:`Future.set_result` method).
+

-- 
Repository URL: http://hg.python.org/cpython


More information about the Python-checkins mailing list