blob: 166ab738783b997d120a22088af2372642ab8902 [file] [log] [blame]
R David Murray6a143812013-12-20 14:37:39 -05001.. currentmodule:: asyncio
Victor Stinnerea3183f2013-12-03 01:08:00 +01002
3Tasks and coroutines
4====================
5
6.. _coroutine:
7
8Coroutines
9----------
10
Yury Selivanov66f88282015-06-24 11:04:15 -040011Coroutines used with :mod:`asyncio` may be implemented using the
12:keyword:`async def` statement, or by using :term:`generators <generator>`.
13The :keyword:`async def` type of coroutine was added in Python 3.5, and
14is recommended if there is no need to support older Python versions.
Victor Stinnerea3183f2013-12-03 01:08:00 +010015
Yury Selivanov66f88282015-06-24 11:04:15 -040016Generator-based coroutines should be decorated with :func:`@asyncio.coroutine
17<asyncio.coroutine>`, although this is not strictly enforced.
18The decorator enables compatibility with :keyword:`async def` coroutines,
19and also serves as documentation. Generator-based
20coroutines use the ``yield from`` syntax introduced in :pep:`380`,
Victor Stinnerea3183f2013-12-03 01:08:00 +010021instead of the original ``yield`` syntax.
22
23The word "coroutine", like the word "generator", is used for two
24different (though related) concepts:
25
Yury Selivanov66f88282015-06-24 11:04:15 -040026- The function that defines a coroutine
27 (a function definition using :keyword:`async def` or
Victor Stinner59759ff2014-01-16 19:30:21 +010028 decorated with ``@asyncio.coroutine``). If disambiguation is needed
Victor Stinner1ad5afc2014-01-30 00:18:50 +010029 we will call this a *coroutine function* (:func:`iscoroutinefunction`
30 returns ``True``).
Victor Stinnerea3183f2013-12-03 01:08:00 +010031
32- The object obtained by calling a coroutine function. This object
33 represents a computation or an I/O operation (usually a combination)
34 that will complete eventually. If disambiguation is needed we will
Victor Stinner1ad5afc2014-01-30 00:18:50 +010035 call it a *coroutine object* (:func:`iscoroutine` returns ``True``).
Victor Stinnerea3183f2013-12-03 01:08:00 +010036
37Things a coroutine can do:
38
Yury Selivanov66f88282015-06-24 11:04:15 -040039- ``result = await future`` or ``result = yield from future`` --
40 suspends the coroutine until the
Victor Stinnerea3183f2013-12-03 01:08:00 +010041 future is done, then returns the future's result, or raises an
42 exception, which will be propagated. (If the future is cancelled,
43 it will raise a ``CancelledError`` exception.) Note that tasks are
44 futures, and everything said about futures also applies to tasks.
45
Yury Selivanov66f88282015-06-24 11:04:15 -040046- ``result = await coroutine`` or ``result = yield from coroutine`` --
47 wait for another coroutine to
Victor Stinnerea3183f2013-12-03 01:08:00 +010048 produce a result (or raise an exception, which will be propagated).
49 The ``coroutine`` expression must be a *call* to another coroutine.
50
51- ``return expression`` -- produce a result to the coroutine that is
Yury Selivanov66f88282015-06-24 11:04:15 -040052 waiting for this one using :keyword:`await` or ``yield from``.
Victor Stinnerea3183f2013-12-03 01:08:00 +010053
54- ``raise exception`` -- raise an exception in the coroutine that is
Yury Selivanov66f88282015-06-24 11:04:15 -040055 waiting for this one using :keyword:`await` or ``yield from``.
Victor Stinnerea3183f2013-12-03 01:08:00 +010056
Yury Selivanov66f88282015-06-24 11:04:15 -040057Calling a coroutine does not start its code running --
58the coroutine object returned by the call doesn't do anything until you
59schedule its execution. There are two basic ways to start it running:
60call ``await coroutine`` or ``yield from coroutine`` from another coroutine
Victor Stinner530ef2f2014-07-08 12:39:10 +020061(assuming the other coroutine is already running!), or schedule its execution
Yury Selivanov04356e12015-06-30 22:13:22 -040062using the :func:`ensure_future` function or the :meth:`BaseEventLoop.create_task`
Victor Stinner337e03f2014-08-11 01:11:13 +020063method.
64
Victor Stinnerea3183f2013-12-03 01:08:00 +010065
66Coroutines (and tasks) can only run when the event loop is running.
67
Victor Stinnerdb39a0d2014-01-16 18:58:01 +010068.. decorator:: coroutine
69
Yury Selivanov66f88282015-06-24 11:04:15 -040070 Decorator to mark generator-based coroutines. This enables
71 the generator use :keyword:`!yield from` to call :keyword:`async
72 def` coroutines, and also enables the generator to be called by
73 :keyword:`async def` coroutines, for instance using an
74 :keyword:`await` expression.
Victor Stinnerdb39a0d2014-01-16 18:58:01 +010075
Yury Selivanov66f88282015-06-24 11:04:15 -040076 There is no need to decorate :keyword:`async def` coroutines themselves.
77
78 If the generator is not yielded from before it is destroyed, an error
Victor Stinnerdb39a0d2014-01-16 18:58:01 +010079 message is logged. See :ref:`Detect coroutines never scheduled
80 <asyncio-coroutine-not-scheduled>`.
81
Yury Selivanov37f15bc2014-02-20 16:20:44 -050082.. note::
83
84 In this documentation, some methods are documented as coroutines,
85 even if they are plain Python functions returning a :class:`Future`.
86 This is intentional to have a freedom of tweaking the implementation
87 of these functions in the future. If such a function is needed to be
Yury Selivanov04356e12015-06-30 22:13:22 -040088 used in a callback-style code, wrap its result with :func:`ensure_future`.
Yury Selivanov37f15bc2014-02-20 16:20:44 -050089
Victor Stinnerea3183f2013-12-03 01:08:00 +010090
Victor Stinnerb69d62d2013-12-10 02:09:46 +010091.. _asyncio-hello-world-coroutine:
92
Victor Stinner7f314ed2014-10-15 18:49:16 +020093Example: Hello World coroutine
94^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinnerb69d62d2013-12-10 02:09:46 +010095
Victor Stinner7f314ed2014-10-15 18:49:16 +020096Example of coroutine displaying ``"Hello World"``::
Victor Stinnerb69d62d2013-12-10 02:09:46 +010097
98 import asyncio
99
Yury Selivanov66f88282015-06-24 11:04:15 -0400100 async def hello_world():
Victor Stinner7f314ed2014-10-15 18:49:16 +0200101 print("Hello World!")
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100102
103 loop = asyncio.get_event_loop()
Victor Stinner7f314ed2014-10-15 18:49:16 +0200104 # Blocking call which returns when the hello_world() coroutine is done
105 loop.run_until_complete(hello_world())
106 loop.close()
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100107
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100108.. seealso::
109
Victor Stinner7f314ed2014-10-15 18:49:16 +0200110 The :ref:`Hello World with call_soon() <asyncio-hello-world-callback>`
111 example uses the :meth:`BaseEventLoop.call_soon` method to schedule a
112 callback.
113
114
115.. _asyncio-date-coroutine:
116
117Example: Coroutine displaying the current date
118^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
119
120Example of coroutine displaying the current date every second during 5 seconds
121using the :meth:`sleep` function::
122
123 import asyncio
124 import datetime
125
Yury Selivanov66f88282015-06-24 11:04:15 -0400126 async def display_date(loop):
127 end_time = loop.time() + 5.0
128 while True:
129 print(datetime.datetime.now())
130 if (loop.time() + 1.0) >= end_time:
131 break
132 await asyncio.sleep(1)
133
134 loop = asyncio.get_event_loop()
135 # Blocking call which returns when the display_date() coroutine is done
136 loop.run_until_complete(display_date(loop))
137 loop.close()
138
139The same coroutine implemented using a generator::
140
Victor Stinner7f314ed2014-10-15 18:49:16 +0200141 @asyncio.coroutine
142 def display_date(loop):
143 end_time = loop.time() + 5.0
144 while True:
145 print(datetime.datetime.now())
146 if (loop.time() + 1.0) >= end_time:
147 break
148 yield from asyncio.sleep(1)
149
Victor Stinner7f314ed2014-10-15 18:49:16 +0200150.. seealso::
151
152 The :ref:`display the current date with call_later()
153 <asyncio-date-callback>` example uses a callback with the
154 :meth:`BaseEventLoop.call_later` method.
155
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100156
157Example: Chain coroutines
158^^^^^^^^^^^^^^^^^^^^^^^^^
159
160Example chaining coroutines::
161
162 import asyncio
163
Yury Selivanov66f88282015-06-24 11:04:15 -0400164 async def compute(x, y):
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100165 print("Compute %s + %s ..." % (x, y))
Yury Selivanov66f88282015-06-24 11:04:15 -0400166 await asyncio.sleep(1.0)
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100167 return x + y
168
Yury Selivanov66f88282015-06-24 11:04:15 -0400169 async def print_sum(x, y):
170 result = await compute(x, y)
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100171 print("%s + %s = %s" % (x, y, result))
172
173 loop = asyncio.get_event_loop()
174 loop.run_until_complete(print_sum(1, 2))
Victor Stinnerf40c6632014-01-28 23:32:40 +0100175 loop.close()
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100176
177``compute()`` is chained to ``print_sum()``: ``print_sum()`` coroutine waits
Brian Curtina1afeec2014-02-08 18:36:14 -0600178until ``compute()`` is completed before returning its result.
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100179
Victor Stinner1c4b8922013-12-12 12:35:17 +0100180Sequence diagram of the example:
181
182.. image:: tulip_coro.png
183 :align: center
184
Victor Stinner86e139a2013-12-13 12:51:24 +0100185The "Task" is created by the :meth:`BaseEventLoop.run_until_complete` method
Victor Stinner59759ff2014-01-16 19:30:21 +0100186when it gets a coroutine object instead of a task.
Victor Stinner86e139a2013-12-13 12:51:24 +0100187
188The diagram shows the control flow, it does not describe exactly how things
189work internally. For example, the sleep coroutine creates an internal future
190which uses :meth:`BaseEventLoop.call_later` to wake up the task in 1 second.
Victor Stinner1c4b8922013-12-12 12:35:17 +0100191
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100192
Victor Stinner99c2ab42013-12-03 19:17:25 +0100193InvalidStateError
194-----------------
195
196.. exception:: InvalidStateError
197
198 The operation is not allowed in this state.
199
200
Victor Stinner28d0ae482014-05-29 00:04:57 +0200201TimeoutError
202------------
203
204.. exception:: TimeoutError
205
206 The operation exceeded the given deadline.
207
208.. note::
209
210 This exception is different from the builtin :exc:`TimeoutError` exception!
211
212
Victor Stinner99c2ab42013-12-03 19:17:25 +0100213Future
214------
215
216.. class:: Future(\*, loop=None)
217
218 This class is *almost* compatible with :class:`concurrent.futures.Future`.
219
220 Differences:
221
222 - :meth:`result` and :meth:`exception` do not take a timeout argument and
223 raise an exception when the future isn't done yet.
224
225 - Callbacks registered with :meth:`add_done_callback` are always called
226 via the event loop's :meth:`~BaseEventLoop.call_soon_threadsafe`.
227
228 - This class is not compatible with the :func:`~concurrent.futures.wait` and
229 :func:`~concurrent.futures.as_completed` functions in the
230 :mod:`concurrent.futures` package.
231
Victor Stinner83704962015-02-25 14:24:15 +0100232 This class is :ref:`not thread safe <asyncio-multithreading>`.
233
Victor Stinner99c2ab42013-12-03 19:17:25 +0100234 .. method:: cancel()
235
236 Cancel the future and schedule callbacks.
237
238 If the future is already done or cancelled, return ``False``. Otherwise,
239 change the future's state to cancelled, schedule the callbacks and return
240 ``True``.
241
242 .. method:: cancelled()
243
244 Return ``True`` if the future was cancelled.
245
246 .. method:: done()
247
248 Return True if the future is done.
249
250 Done means either that a result / exception are available, or that the
251 future was cancelled.
252
253 .. method:: result()
254
255 Return the result this future represents.
256
257 If the future has been cancelled, raises :exc:`CancelledError`. If the
258 future's result isn't yet available, raises :exc:`InvalidStateError`. If
259 the future is done and has an exception set, this exception is raised.
260
261 .. method:: exception()
262
263 Return the exception that was set on this future.
264
265 The exception (or ``None`` if no exception was set) is returned only if
266 the future is done. If the future has been cancelled, raises
267 :exc:`CancelledError`. If the future isn't done yet, raises
268 :exc:`InvalidStateError`.
269
270 .. method:: add_done_callback(fn)
271
272 Add a callback to be run when the future becomes done.
273
274 The callback is called with a single argument - the future object. If the
275 future is already done when this is called, the callback is scheduled
276 with :meth:`~BaseEventLoop.call_soon`.
277
Victor Stinner8464c242014-11-28 13:15:41 +0100278 :ref:`Use functools.partial to pass parameters to the callback
279 <asyncio-pass-keywords>`. For example,
280 ``fut.add_done_callback(functools.partial(print, "Future:",
281 flush=True))`` will call ``print("Future:", fut, flush=True)``.
282
Victor Stinner99c2ab42013-12-03 19:17:25 +0100283 .. method:: remove_done_callback(fn)
284
285 Remove all instances of a callback from the "call when done" list.
286
287 Returns the number of callbacks removed.
288
289 .. method:: set_result(result)
290
291 Mark the future done and set its result.
292
293 If the future is already done when this method is called, raises
294 :exc:`InvalidStateError`.
295
296 .. method:: set_exception(exception)
297
298 Mark the future done and set an exception.
299
300 If the future is already done when this method is called, raises
301 :exc:`InvalidStateError`.
302
303
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100304Example: Future with run_until_complete()
305^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
306
Victor Stinner59759ff2014-01-16 19:30:21 +0100307Example combining a :class:`Future` and a :ref:`coroutine function
308<coroutine>`::
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100309
310 import asyncio
311
312 @asyncio.coroutine
313 def slow_operation(future):
314 yield from asyncio.sleep(1)
Victor Stinner04e05da2014-02-17 10:54:30 +0100315 future.set_result('Future is done!')
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100316
317 loop = asyncio.get_event_loop()
318 future = asyncio.Future()
Yury Selivanovd7e19bb2015-05-11 16:33:41 -0400319 asyncio.ensure_future(slow_operation(future))
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100320 loop.run_until_complete(future)
321 print(future.result())
Victor Stinnerf40c6632014-01-28 23:32:40 +0100322 loop.close()
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100323
Terry Jan Reedyc935a952014-07-24 02:33:14 -0400324The coroutine function is responsible for the computation (which takes 1 second)
Victor Stinner59759ff2014-01-16 19:30:21 +0100325and it stores the result into the future. The
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100326:meth:`~BaseEventLoop.run_until_complete` method waits for the completion of
327the future.
328
329.. note::
330 The :meth:`~BaseEventLoop.run_until_complete` method uses internally the
331 :meth:`~Future.add_done_callback` method to be notified when the future is
332 done.
333
334
335Example: Future with run_forever()
336^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
337
338The previous example can be written differently using the
339:meth:`Future.add_done_callback` method to describe explicitly the control
340flow::
341
342 import asyncio
343
344 @asyncio.coroutine
345 def slow_operation(future):
346 yield from asyncio.sleep(1)
Victor Stinner04e05da2014-02-17 10:54:30 +0100347 future.set_result('Future is done!')
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100348
349 def got_result(future):
350 print(future.result())
351 loop.stop()
352
353 loop = asyncio.get_event_loop()
354 future = asyncio.Future()
Yury Selivanovd7e19bb2015-05-11 16:33:41 -0400355 asyncio.ensure_future(slow_operation(future))
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100356 future.add_done_callback(got_result)
Victor Stinner04e05da2014-02-17 10:54:30 +0100357 try:
358 loop.run_forever()
359 finally:
360 loop.close()
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100361
Victor Stinner039f7032014-12-02 17:52:45 +0100362In this example, the future is used to link ``slow_operation()`` to
363``got_result()``: when ``slow_operation()`` is done, ``got_result()`` is called
364with the result.
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100365
366
Victor Stinnerea3183f2013-12-03 01:08:00 +0100367Task
368----
369
370.. class:: Task(coro, \*, loop=None)
371
Victor Stinner530ef2f2014-07-08 12:39:10 +0200372 Schedule the execution of a :ref:`coroutine <coroutine>`: wrap it in a
373 future. A task is a subclass of :class:`Future`.
374
R David Murray22dd8332014-09-24 11:09:09 -0400375 A task is responsible for executing a coroutine object in an event loop. If
Victor Stinner530ef2f2014-07-08 12:39:10 +0200376 the wrapped coroutine yields from a future, the task suspends the execution
377 of the wrapped coroutine and waits for the completition of the future. When
378 the future is done, the execution of the wrapped coroutine restarts with the
379 result or the exception of the future.
380
381 Event loops use cooperative scheduling: an event loop only runs one task at
R David Murray22dd8332014-09-24 11:09:09 -0400382 a time. Other tasks may run in parallel if other event loops are
Victor Stinner530ef2f2014-07-08 12:39:10 +0200383 running in different threads. While a task waits for the completion of a
384 future, the event loop executes a new task.
385
R David Murray22dd8332014-09-24 11:09:09 -0400386 The cancellation of a task is different from the cancelation of a future. Calling
Victor Stinner530ef2f2014-07-08 12:39:10 +0200387 :meth:`cancel` will throw a :exc:`~concurrent.futures.CancelledError` to the
388 wrapped coroutine. :meth:`~Future.cancelled` only returns ``True`` if the
389 wrapped coroutine did not catch the
390 :exc:`~concurrent.futures.CancelledError` exception, or raised a
391 :exc:`~concurrent.futures.CancelledError` exception.
392
393 If a pending task is destroyed, the execution of its wrapped :ref:`coroutine
394 <coroutine>` did not complete. It is probably a bug and a warning is
395 logged: see :ref:`Pending task destroyed <asyncio-pending-task-destroyed>`.
396
Yury Selivanov04356e12015-06-30 22:13:22 -0400397 Don't directly create :class:`Task` instances: use the :func:`ensure_future`
Victor Stinner337e03f2014-08-11 01:11:13 +0200398 function or the :meth:`BaseEventLoop.create_task` method.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100399
Victor Stinner83704962015-02-25 14:24:15 +0100400 This class is :ref:`not thread safe <asyncio-multithreading>`.
401
Victor Stinnerea3183f2013-12-03 01:08:00 +0100402 .. classmethod:: all_tasks(loop=None)
403
404 Return a set of all tasks for an event loop.
405
406 By default all tasks for the current event loop are returned.
407
Victor Stinner742520b2013-12-10 12:14:50 +0100408 .. classmethod:: current_task(loop=None)
409
410 Return the currently running task in an event loop or ``None``.
411
412 By default the current task for the current event loop is returned.
413
414 ``None`` is returned when called not in the context of a :class:`Task`.
415
Victor Stinner8d213572014-06-02 23:06:46 +0200416 .. method:: cancel()
417
R David Murray22dd8332014-09-24 11:09:09 -0400418 Request that this task cancel itself.
Victor Stinner8d213572014-06-02 23:06:46 +0200419
420 This arranges for a :exc:`~concurrent.futures.CancelledError` to be
421 thrown into the wrapped coroutine on the next cycle through the event
422 loop. The coroutine then has a chance to clean up or even deny the
423 request using try/except/finally.
424
R David Murray22dd8332014-09-24 11:09:09 -0400425 Unlike :meth:`Future.cancel`, this does not guarantee that the task
Victor Stinner8d213572014-06-02 23:06:46 +0200426 will be cancelled: the exception might be caught and acted upon, delaying
R David Murray22dd8332014-09-24 11:09:09 -0400427 cancellation of the task or preventing cancellation completely. The task
428 may also return a value or raise a different exception.
Victor Stinner8d213572014-06-02 23:06:46 +0200429
430 Immediately after this method is called, :meth:`~Future.cancelled` will
431 not return ``True`` (unless the task was already cancelled). A task will
432 be marked as cancelled when the wrapped coroutine terminates with a
433 :exc:`~concurrent.futures.CancelledError` exception (even if
434 :meth:`cancel` was not called).
435
436 .. method:: get_stack(\*, limit=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100437
438 Return the list of stack frames for this task's coroutine.
439
Victor Stinnerd87de832014-12-02 17:57:04 +0100440 If the coroutine is not done, this returns the stack where it is suspended.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100441 If the coroutine has completed successfully or was cancelled, this
442 returns an empty list. If the coroutine was terminated by an exception,
443 this returns the list of traceback frames.
444
445 The frames are always ordered from oldest to newest.
446
Brian Curtina1afeec2014-02-08 18:36:14 -0600447 The optional limit gives the maximum number of frames to return; by
Victor Stinnerea3183f2013-12-03 01:08:00 +0100448 default all available frames are returned. Its meaning differs depending
449 on whether a stack or a traceback is returned: the newest frames of a
450 stack are returned, but the oldest frames of a traceback are returned.
451 (This matches the behavior of the traceback module.)
452
453 For reasons beyond our control, only one stack frame is returned for a
454 suspended coroutine.
455
456 .. method:: print_stack(\*, limit=None, file=None)
457
458 Print the stack or traceback for this task's coroutine.
459
460 This produces output similar to that of the traceback module, for the
461 frames retrieved by get_stack(). The limit argument is passed to
462 get_stack(). The file argument is an I/O stream to which the output
R David Murray22dd8332014-09-24 11:09:09 -0400463 is written; by default output is written to sys.stderr.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100464
465
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100466Example: Parallel execution of tasks
467^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
468
469Example executing 3 tasks (A, B, C) in parallel::
470
471 import asyncio
472
473 @asyncio.coroutine
Victor Stinner34f29462013-12-10 02:51:05 +0100474 def factorial(name, number):
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100475 f = 1
Victor Stinner34f29462013-12-10 02:51:05 +0100476 for i in range(2, number+1):
477 print("Task %s: Compute factorial(%s)..." % (name, i))
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100478 yield from asyncio.sleep(1)
Victor Stinner34f29462013-12-10 02:51:05 +0100479 f *= i
480 print("Task %s: factorial(%s) = %s" % (name, number, f))
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100481
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100482 loop = asyncio.get_event_loop()
Victor Stinner530ef2f2014-07-08 12:39:10 +0200483 tasks = [
Yury Selivanovd7e19bb2015-05-11 16:33:41 -0400484 asyncio.ensure_future(factorial("A", 2)),
485 asyncio.ensure_future(factorial("B", 3)),
486 asyncio.ensure_future(factorial("C", 4))]
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100487 loop.run_until_complete(asyncio.wait(tasks))
Victor Stinnerf40c6632014-01-28 23:32:40 +0100488 loop.close()
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100489
490Output::
491
Victor Stinner34f29462013-12-10 02:51:05 +0100492 Task A: Compute factorial(2)...
493 Task B: Compute factorial(2)...
494 Task C: Compute factorial(2)...
495 Task A: factorial(2) = 2
496 Task B: Compute factorial(3)...
497 Task C: Compute factorial(3)...
498 Task B: factorial(3) = 6
499 Task C: Compute factorial(4)...
500 Task C: factorial(4) = 24
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100501
Victor Stinner34f29462013-12-10 02:51:05 +0100502A task is automatically scheduled for execution when it is created. The event
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100503loop stops when all tasks are done.
504
505
Victor Stinnerea3183f2013-12-03 01:08:00 +0100506Task functions
507--------------
508
Eli Bendersky029981b2014-01-20 07:02:22 -0800509.. note::
510
511 In the functions below, the optional *loop* argument allows to explicitly set
512 the event loop object used by the underlying task or coroutine. If it's
513 not provided, the default event loop is used.
514
Victor Stinner99c2ab42013-12-03 19:17:25 +0100515.. function:: as_completed(fs, \*, loop=None, timeout=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100516
Victor Stinner99c2ab42013-12-03 19:17:25 +0100517 Return an iterator whose values, when waited for, are :class:`Future`
518 instances.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100519
Victor Stinner28d0ae482014-05-29 00:04:57 +0200520 Raises :exc:`asyncio.TimeoutError` if the timeout occurs before all Futures
521 are done.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100522
523 Example::
524
525 for f in as_completed(fs):
526 result = yield from f # The 'yield from' may raise
527 # Use result
528
529 .. note::
530
531 The futures ``f`` are not necessarily members of fs.
532
Yury Selivanovd7e19bb2015-05-11 16:33:41 -0400533.. function:: ensure_future(coro_or_future, \*, loop=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100534
Victor Stinner980dd842014-10-12 21:36:17 +0200535 Schedule the execution of a :ref:`coroutine object <coroutine>`: wrap it in
536 a future. Return a :class:`Task` object.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100537
Victor Stinner99c2ab42013-12-03 19:17:25 +0100538 If the argument is a :class:`Future`, it is returned directly.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100539
Yury Selivanovd7e19bb2015-05-11 16:33:41 -0400540 .. versionadded:: 3.4.4
541
Victor Stinner337e03f2014-08-11 01:11:13 +0200542 .. seealso::
543
544 The :meth:`BaseEventLoop.create_task` method.
545
Yury Selivanovd7e19bb2015-05-11 16:33:41 -0400546.. function:: async(coro_or_future, \*, loop=None)
547
548 A deprecated alias to :func:`ensure_future`.
549
550 .. deprecated:: 3.4.4
551
Victor Stinner99c2ab42013-12-03 19:17:25 +0100552.. function:: gather(\*coros_or_futures, loop=None, return_exceptions=False)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100553
Victor Stinner59759ff2014-01-16 19:30:21 +0100554 Return a future aggregating results from the given coroutine objects or
555 futures.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100556
557 All futures must share the same event loop. If all the tasks are done
558 successfully, the returned future's result is the list of results (in the
559 order of the original sequence, not necessarily the order of results
Victor Stinner12c68b22014-02-09 01:35:24 +0100560 arrival). If *return_exceptions* is True, exceptions in the tasks are
Victor Stinnerea3183f2013-12-03 01:08:00 +0100561 treated the same as successful results, and gathered in the result list;
562 otherwise, the first raised exception will be immediately propagated to the
563 returned future.
564
565 Cancellation: if the outer Future is cancelled, all children (that have not
566 completed yet) are also cancelled. If any child is cancelled, this is
567 treated as if it raised :exc:`~concurrent.futures.CancelledError` -- the
568 outer Future is *not* cancelled in this case. (This is to prevent the
569 cancellation of one child to cause other children to be cancelled.)
570
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100571.. function:: iscoroutine(obj)
572
Yury Selivanov66f88282015-06-24 11:04:15 -0400573 Return ``True`` if *obj* is a :ref:`coroutine object <coroutine>`,
574 which may be based on a generator or an :keyword:`async def` coroutine.
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100575
Yury Selivanov66f88282015-06-24 11:04:15 -0400576.. function:: iscoroutinefunction(func)
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100577
Yury Selivanov66f88282015-06-24 11:04:15 -0400578 Return ``True`` if *func* is determined to be a :ref:`coroutine function
579 <coroutine>`, which may be a decorated generator function or an
580 :keyword:`async def` function.
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100581
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100582.. coroutinefunction:: sleep(delay, result=None, \*, loop=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100583
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500584 Create a :ref:`coroutine <coroutine>` that completes after a given
Eli Bendersky2d26af82014-01-20 06:59:23 -0800585 time (in seconds). If *result* is provided, it is produced to the caller
586 when the coroutine completes.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100587
Victor Stinner45b27ed2014-02-01 02:36:43 +0100588 The resolution of the sleep depends on the :ref:`granularity of the event
589 loop <asyncio-delayed-calls>`.
590
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100591 This function is a :ref:`coroutine <coroutine>`.
592
Victor Stinnerea3183f2013-12-03 01:08:00 +0100593.. function:: shield(arg, \*, loop=None)
594
595 Wait for a future, shielding it from cancellation.
596
597 The statement::
598
599 res = yield from shield(something())
600
601 is exactly equivalent to the statement::
602
603 res = yield from something()
604
605 *except* that if the coroutine containing it is cancelled, the task running
606 in ``something()`` is not cancelled. From the point of view of
607 ``something()``, the cancellation did not happen. But its caller is still
608 cancelled, so the yield-from expression still raises
609 :exc:`~concurrent.futures.CancelledError`. Note: If ``something()`` is
610 cancelled by other means this will still cancel ``shield()``.
611
612 If you want to completely ignore cancellation (not recommended) you can
613 combine ``shield()`` with a try/except clause, as follows::
614
615 try:
616 res = yield from shield(something())
617 except CancelledError:
618 res = None
619
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100620.. coroutinefunction:: wait(futures, \*, loop=None, timeout=None, return_when=ALL_COMPLETED)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100621
Victor Stinner59759ff2014-01-16 19:30:21 +0100622 Wait for the Futures and coroutine objects given by the sequence *futures*
623 to complete. Coroutines will be wrapped in Tasks. Returns two sets of
Victor Stinner99c2ab42013-12-03 19:17:25 +0100624 :class:`Future`: (done, pending).
Victor Stinnerea3183f2013-12-03 01:08:00 +0100625
Victor Stinnerdb74d982014-06-10 11:16:05 +0200626 The sequence *futures* must not be empty.
627
Victor Stinnerea3183f2013-12-03 01:08:00 +0100628 *timeout* can be used to control the maximum number of seconds to wait before
629 returning. *timeout* can be an int or float. If *timeout* is not specified
630 or ``None``, there is no limit to the wait time.
631
632 *return_when* indicates when this function should return. It must be one of
Victor Stinner933a8c82013-12-03 01:59:38 +0100633 the following constants of the :mod:`concurrent.futures` module:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100634
635 .. tabularcolumns:: |l|L|
636
637 +-----------------------------+----------------------------------------+
638 | Constant | Description |
639 +=============================+========================================+
640 | :const:`FIRST_COMPLETED` | The function will return when any |
641 | | future finishes or is cancelled. |
642 +-----------------------------+----------------------------------------+
643 | :const:`FIRST_EXCEPTION` | The function will return when any |
644 | | future finishes by raising an |
645 | | exception. If no future raises an |
646 | | exception then it is equivalent to |
647 | | :const:`ALL_COMPLETED`. |
648 +-----------------------------+----------------------------------------+
649 | :const:`ALL_COMPLETED` | The function will return when all |
650 | | futures finish or are cancelled. |
651 +-----------------------------+----------------------------------------+
652
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500653 This function is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100654
655 Usage::
656
657 done, pending = yield from asyncio.wait(fs)
658
659 .. note::
660
Victor Stinner28d0ae482014-05-29 00:04:57 +0200661 This does not raise :exc:`asyncio.TimeoutError`! Futures that aren't done
662 when the timeout occurs are returned in the second set.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100663
Victor Stinner3e09e322013-12-03 01:22:06 +0100664
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100665.. coroutinefunction:: wait_for(fut, timeout, \*, loop=None)
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100666
667 Wait for the single :class:`Future` or :ref:`coroutine object <coroutine>`
Victor Stinner530ef2f2014-07-08 12:39:10 +0200668 to complete with timeout. If *timeout* is ``None``, block until the future
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100669 completes.
670
Victor Stinner337e03f2014-08-11 01:11:13 +0200671 Coroutine will be wrapped in :class:`Task`.
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100672
673 Returns result of the Future or coroutine. When a timeout occurs, it
Victor Stinner28d0ae482014-05-29 00:04:57 +0200674 cancels the task and raises :exc:`asyncio.TimeoutError`. To avoid the task
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100675 cancellation, wrap it in :func:`shield`.
676
Victor Stinner72dcb0a2015-04-03 17:08:19 +0200677 If the wait is cancelled, the future *fut* is also cancelled.
678
Victor Stinner530ef2f2014-07-08 12:39:10 +0200679 This function is a :ref:`coroutine <coroutine>`, usage::
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500680
Victor Stinner530ef2f2014-07-08 12:39:10 +0200681 result = yield from asyncio.wait_for(fut, 60.0)
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100682
Victor Stinner72dcb0a2015-04-03 17:08:19 +0200683 .. versionchanged:: 3.4.3
684 If the wait is cancelled, the future *fut* is now also cancelled.
685