blob: fa95ca980401b236df01912ba3256af9e66286de [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
11A coroutine is a generator that follows certain conventions. For
12documentation purposes, all coroutines should be decorated with
13``@asyncio.coroutine``, but this cannot be strictly enforced.
14
15Coroutines use the ``yield from`` syntax introduced in :pep:`380`,
16instead of the original ``yield`` syntax.
17
18The word "coroutine", like the word "generator", is used for two
19different (though related) concepts:
20
21- The function that defines a coroutine (a function definition
Victor Stinner59759ff2014-01-16 19:30:21 +010022 decorated with ``@asyncio.coroutine``). If disambiguation is needed
Victor Stinner1ad5afc2014-01-30 00:18:50 +010023 we will call this a *coroutine function* (:func:`iscoroutinefunction`
24 returns ``True``).
Victor Stinnerea3183f2013-12-03 01:08:00 +010025
26- The object obtained by calling a coroutine function. This object
27 represents a computation or an I/O operation (usually a combination)
28 that will complete eventually. If disambiguation is needed we will
Victor Stinner1ad5afc2014-01-30 00:18:50 +010029 call it a *coroutine object* (:func:`iscoroutine` returns ``True``).
Victor Stinnerea3183f2013-12-03 01:08:00 +010030
31Things a coroutine can do:
32
33- ``result = yield from future`` -- suspends the coroutine until the
34 future is done, then returns the future's result, or raises an
35 exception, which will be propagated. (If the future is cancelled,
36 it will raise a ``CancelledError`` exception.) Note that tasks are
37 futures, and everything said about futures also applies to tasks.
38
39- ``result = yield from coroutine`` -- wait for another coroutine to
40 produce a result (or raise an exception, which will be propagated).
41 The ``coroutine`` expression must be a *call* to another coroutine.
42
43- ``return expression`` -- produce a result to the coroutine that is
44 waiting for this one using ``yield from``.
45
46- ``raise exception`` -- raise an exception in the coroutine that is
47 waiting for this one using ``yield from``.
48
49Calling a coroutine does not start its code running -- it is just a
50generator, and the coroutine object returned by the call is really a
51generator object, which doesn't do anything until you iterate over it.
52In the case of a coroutine object, there are two basic ways to start
53it running: call ``yield from coroutine`` from another coroutine
Victor Stinner530ef2f2014-07-08 12:39:10 +020054(assuming the other coroutine is already running!), or schedule its execution
Victor Stinner337e03f2014-08-11 01:11:13 +020055using the :func:`async` function or the :meth:`BaseEventLoop.create_task`
56method.
57
Victor Stinnerea3183f2013-12-03 01:08:00 +010058
59Coroutines (and tasks) can only run when the event loop is running.
60
Victor Stinnerdb39a0d2014-01-16 18:58:01 +010061.. decorator:: coroutine
62
63 Decorator to mark coroutines.
64
65 If the coroutine is not yielded from before it is destroyed, an error
66 message is logged. See :ref:`Detect coroutines never scheduled
67 <asyncio-coroutine-not-scheduled>`.
68
Yury Selivanov37f15bc2014-02-20 16:20:44 -050069.. note::
70
71 In this documentation, some methods are documented as coroutines,
72 even if they are plain Python functions returning a :class:`Future`.
73 This is intentional to have a freedom of tweaking the implementation
74 of these functions in the future. If such a function is needed to be
75 used in a callback-style code, wrap its result with :func:`async`.
76
Victor Stinnerea3183f2013-12-03 01:08:00 +010077
Victor Stinnerb69d62d2013-12-10 02:09:46 +010078.. _asyncio-hello-world-coroutine:
79
80Example: "Hello World" coroutine
81^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
82
83Print ``"Hello World"`` every two seconds using a coroutine::
84
85 import asyncio
86
87 @asyncio.coroutine
88 def greet_every_two_seconds():
89 while True:
90 print('Hello World')
91 yield from asyncio.sleep(2)
92
93 loop = asyncio.get_event_loop()
Victor Stinner63b21a82014-07-05 15:38:59 +020094 try:
95 loop.run_until_complete(greet_every_two_seconds())
96 finally:
97 loop.close()
Victor Stinnerb69d62d2013-12-10 02:09:46 +010098
Victor Stinnerb69d62d2013-12-10 02:09:46 +010099.. seealso::
100
Victor Stinner6888b962014-10-11 16:15:58 +0200101 The :ref:`Hello World with a callback <asyncio-hello-world-callback>`
102 example uses a callback scheduled by the :meth:`BaseEventLoop.call_soon`
103 method.
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100104
105Example: Chain coroutines
106^^^^^^^^^^^^^^^^^^^^^^^^^
107
108Example chaining coroutines::
109
110 import asyncio
111
112 @asyncio.coroutine
113 def compute(x, y):
114 print("Compute %s + %s ..." % (x, y))
115 yield from asyncio.sleep(1.0)
116 return x + y
117
118 @asyncio.coroutine
119 def print_sum(x, y):
120 result = yield from compute(x, y)
121 print("%s + %s = %s" % (x, y, result))
122
123 loop = asyncio.get_event_loop()
124 loop.run_until_complete(print_sum(1, 2))
Victor Stinnerf40c6632014-01-28 23:32:40 +0100125 loop.close()
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100126
127``compute()`` is chained to ``print_sum()``: ``print_sum()`` coroutine waits
Brian Curtina1afeec2014-02-08 18:36:14 -0600128until ``compute()`` is completed before returning its result.
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100129
Victor Stinner1c4b8922013-12-12 12:35:17 +0100130Sequence diagram of the example:
131
132.. image:: tulip_coro.png
133 :align: center
134
Victor Stinner86e139a2013-12-13 12:51:24 +0100135The "Task" is created by the :meth:`BaseEventLoop.run_until_complete` method
Victor Stinner59759ff2014-01-16 19:30:21 +0100136when it gets a coroutine object instead of a task.
Victor Stinner86e139a2013-12-13 12:51:24 +0100137
138The diagram shows the control flow, it does not describe exactly how things
139work internally. For example, the sleep coroutine creates an internal future
140which uses :meth:`BaseEventLoop.call_later` to wake up the task in 1 second.
Victor Stinner1c4b8922013-12-12 12:35:17 +0100141
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100142
Victor Stinner99c2ab42013-12-03 19:17:25 +0100143InvalidStateError
144-----------------
145
146.. exception:: InvalidStateError
147
148 The operation is not allowed in this state.
149
150
Victor Stinner28d0ae482014-05-29 00:04:57 +0200151TimeoutError
152------------
153
154.. exception:: TimeoutError
155
156 The operation exceeded the given deadline.
157
158.. note::
159
160 This exception is different from the builtin :exc:`TimeoutError` exception!
161
162
Victor Stinner99c2ab42013-12-03 19:17:25 +0100163Future
164------
165
166.. class:: Future(\*, loop=None)
167
168 This class is *almost* compatible with :class:`concurrent.futures.Future`.
169
170 Differences:
171
172 - :meth:`result` and :meth:`exception` do not take a timeout argument and
173 raise an exception when the future isn't done yet.
174
175 - Callbacks registered with :meth:`add_done_callback` are always called
176 via the event loop's :meth:`~BaseEventLoop.call_soon_threadsafe`.
177
178 - This class is not compatible with the :func:`~concurrent.futures.wait` and
179 :func:`~concurrent.futures.as_completed` functions in the
180 :mod:`concurrent.futures` package.
181
182 .. method:: cancel()
183
184 Cancel the future and schedule callbacks.
185
186 If the future is already done or cancelled, return ``False``. Otherwise,
187 change the future's state to cancelled, schedule the callbacks and return
188 ``True``.
189
190 .. method:: cancelled()
191
192 Return ``True`` if the future was cancelled.
193
194 .. method:: done()
195
196 Return True if the future is done.
197
198 Done means either that a result / exception are available, or that the
199 future was cancelled.
200
201 .. method:: result()
202
203 Return the result this future represents.
204
205 If the future has been cancelled, raises :exc:`CancelledError`. If the
206 future's result isn't yet available, raises :exc:`InvalidStateError`. If
207 the future is done and has an exception set, this exception is raised.
208
209 .. method:: exception()
210
211 Return the exception that was set on this future.
212
213 The exception (or ``None`` if no exception was set) is returned only if
214 the future is done. If the future has been cancelled, raises
215 :exc:`CancelledError`. If the future isn't done yet, raises
216 :exc:`InvalidStateError`.
217
218 .. method:: add_done_callback(fn)
219
220 Add a callback to be run when the future becomes done.
221
222 The callback is called with a single argument - the future object. If the
223 future is already done when this is called, the callback is scheduled
224 with :meth:`~BaseEventLoop.call_soon`.
225
226 .. method:: remove_done_callback(fn)
227
228 Remove all instances of a callback from the "call when done" list.
229
230 Returns the number of callbacks removed.
231
232 .. method:: set_result(result)
233
234 Mark the future done and set its result.
235
236 If the future is already done when this method is called, raises
237 :exc:`InvalidStateError`.
238
239 .. method:: set_exception(exception)
240
241 Mark the future done and set an exception.
242
243 If the future is already done when this method is called, raises
244 :exc:`InvalidStateError`.
245
246
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100247Example: Future with run_until_complete()
248^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
249
Victor Stinner59759ff2014-01-16 19:30:21 +0100250Example combining a :class:`Future` and a :ref:`coroutine function
251<coroutine>`::
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100252
253 import asyncio
254
255 @asyncio.coroutine
256 def slow_operation(future):
257 yield from asyncio.sleep(1)
Victor Stinner04e05da2014-02-17 10:54:30 +0100258 future.set_result('Future is done!')
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100259
260 loop = asyncio.get_event_loop()
261 future = asyncio.Future()
Victor Stinner337e03f2014-08-11 01:11:13 +0200262 asyncio.async(slow_operation(future))
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100263 loop.run_until_complete(future)
264 print(future.result())
Victor Stinnerf40c6632014-01-28 23:32:40 +0100265 loop.close()
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100266
Terry Jan Reedyc935a952014-07-24 02:33:14 -0400267The coroutine function is responsible for the computation (which takes 1 second)
Victor Stinner59759ff2014-01-16 19:30:21 +0100268and it stores the result into the future. The
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100269:meth:`~BaseEventLoop.run_until_complete` method waits for the completion of
270the future.
271
272.. note::
273 The :meth:`~BaseEventLoop.run_until_complete` method uses internally the
274 :meth:`~Future.add_done_callback` method to be notified when the future is
275 done.
276
277
278Example: Future with run_forever()
279^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
280
281The previous example can be written differently using the
282:meth:`Future.add_done_callback` method to describe explicitly the control
283flow::
284
285 import asyncio
286
287 @asyncio.coroutine
288 def slow_operation(future):
289 yield from asyncio.sleep(1)
Victor Stinner04e05da2014-02-17 10:54:30 +0100290 future.set_result('Future is done!')
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100291
292 def got_result(future):
293 print(future.result())
294 loop.stop()
295
296 loop = asyncio.get_event_loop()
297 future = asyncio.Future()
Victor Stinner337e03f2014-08-11 01:11:13 +0200298 asyncio.async(slow_operation(future))
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100299 future.add_done_callback(got_result)
Victor Stinner04e05da2014-02-17 10:54:30 +0100300 try:
301 loop.run_forever()
302 finally:
303 loop.close()
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100304
305In this example, the future is responsible to display the result and to stop
306the loop.
307
308.. note::
Victor Stinner59759ff2014-01-16 19:30:21 +0100309 The "slow_operation" coroutine object is only executed when the event loop
310 starts running, so it is possible to add a "done callback" to the future
311 after creating the task scheduling the coroutine object.
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100312
313
314
Victor Stinnerea3183f2013-12-03 01:08:00 +0100315Task
316----
317
318.. class:: Task(coro, \*, loop=None)
319
Victor Stinner530ef2f2014-07-08 12:39:10 +0200320 Schedule the execution of a :ref:`coroutine <coroutine>`: wrap it in a
321 future. A task is a subclass of :class:`Future`.
322
R David Murray22dd8332014-09-24 11:09:09 -0400323 A task is responsible for executing a coroutine object in an event loop. If
Victor Stinner530ef2f2014-07-08 12:39:10 +0200324 the wrapped coroutine yields from a future, the task suspends the execution
325 of the wrapped coroutine and waits for the completition of the future. When
326 the future is done, the execution of the wrapped coroutine restarts with the
327 result or the exception of the future.
328
329 Event loops use cooperative scheduling: an event loop only runs one task at
R David Murray22dd8332014-09-24 11:09:09 -0400330 a time. Other tasks may run in parallel if other event loops are
Victor Stinner530ef2f2014-07-08 12:39:10 +0200331 running in different threads. While a task waits for the completion of a
332 future, the event loop executes a new task.
333
R David Murray22dd8332014-09-24 11:09:09 -0400334 The cancellation of a task is different from the cancelation of a future. Calling
Victor Stinner530ef2f2014-07-08 12:39:10 +0200335 :meth:`cancel` will throw a :exc:`~concurrent.futures.CancelledError` to the
336 wrapped coroutine. :meth:`~Future.cancelled` only returns ``True`` if the
337 wrapped coroutine did not catch the
338 :exc:`~concurrent.futures.CancelledError` exception, or raised a
339 :exc:`~concurrent.futures.CancelledError` exception.
340
341 If a pending task is destroyed, the execution of its wrapped :ref:`coroutine
342 <coroutine>` did not complete. It is probably a bug and a warning is
343 logged: see :ref:`Pending task destroyed <asyncio-pending-task-destroyed>`.
344
R David Murray22dd8332014-09-24 11:09:09 -0400345 Don't directly create :class:`Task` instances: use the :func:`async`
Victor Stinner337e03f2014-08-11 01:11:13 +0200346 function or the :meth:`BaseEventLoop.create_task` method.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100347
348 .. classmethod:: all_tasks(loop=None)
349
350 Return a set of all tasks for an event loop.
351
352 By default all tasks for the current event loop are returned.
353
Victor Stinner742520b2013-12-10 12:14:50 +0100354 .. classmethod:: current_task(loop=None)
355
356 Return the currently running task in an event loop or ``None``.
357
358 By default the current task for the current event loop is returned.
359
360 ``None`` is returned when called not in the context of a :class:`Task`.
361
Victor Stinner8d213572014-06-02 23:06:46 +0200362 .. method:: cancel()
363
R David Murray22dd8332014-09-24 11:09:09 -0400364 Request that this task cancel itself.
Victor Stinner8d213572014-06-02 23:06:46 +0200365
366 This arranges for a :exc:`~concurrent.futures.CancelledError` to be
367 thrown into the wrapped coroutine on the next cycle through the event
368 loop. The coroutine then has a chance to clean up or even deny the
369 request using try/except/finally.
370
R David Murray22dd8332014-09-24 11:09:09 -0400371 Unlike :meth:`Future.cancel`, this does not guarantee that the task
Victor Stinner8d213572014-06-02 23:06:46 +0200372 will be cancelled: the exception might be caught and acted upon, delaying
R David Murray22dd8332014-09-24 11:09:09 -0400373 cancellation of the task or preventing cancellation completely. The task
374 may also return a value or raise a different exception.
Victor Stinner8d213572014-06-02 23:06:46 +0200375
376 Immediately after this method is called, :meth:`~Future.cancelled` will
377 not return ``True`` (unless the task was already cancelled). A task will
378 be marked as cancelled when the wrapped coroutine terminates with a
379 :exc:`~concurrent.futures.CancelledError` exception (even if
380 :meth:`cancel` was not called).
381
382 .. method:: get_stack(\*, limit=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100383
384 Return the list of stack frames for this task's coroutine.
385
386 If the coroutine is active, this returns the stack where it is suspended.
387 If the coroutine has completed successfully or was cancelled, this
388 returns an empty list. If the coroutine was terminated by an exception,
389 this returns the list of traceback frames.
390
391 The frames are always ordered from oldest to newest.
392
Brian Curtina1afeec2014-02-08 18:36:14 -0600393 The optional limit gives the maximum number of frames to return; by
Victor Stinnerea3183f2013-12-03 01:08:00 +0100394 default all available frames are returned. Its meaning differs depending
395 on whether a stack or a traceback is returned: the newest frames of a
396 stack are returned, but the oldest frames of a traceback are returned.
397 (This matches the behavior of the traceback module.)
398
399 For reasons beyond our control, only one stack frame is returned for a
400 suspended coroutine.
401
402 .. method:: print_stack(\*, limit=None, file=None)
403
404 Print the stack or traceback for this task's coroutine.
405
406 This produces output similar to that of the traceback module, for the
407 frames retrieved by get_stack(). The limit argument is passed to
408 get_stack(). The file argument is an I/O stream to which the output
R David Murray22dd8332014-09-24 11:09:09 -0400409 is written; by default output is written to sys.stderr.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100410
411
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100412Example: Parallel execution of tasks
413^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
414
415Example executing 3 tasks (A, B, C) in parallel::
416
417 import asyncio
418
419 @asyncio.coroutine
Victor Stinner34f29462013-12-10 02:51:05 +0100420 def factorial(name, number):
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100421 f = 1
Victor Stinner34f29462013-12-10 02:51:05 +0100422 for i in range(2, number+1):
423 print("Task %s: Compute factorial(%s)..." % (name, i))
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100424 yield from asyncio.sleep(1)
Victor Stinner34f29462013-12-10 02:51:05 +0100425 f *= i
426 print("Task %s: factorial(%s) = %s" % (name, number, f))
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100427
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100428 loop = asyncio.get_event_loop()
Victor Stinner530ef2f2014-07-08 12:39:10 +0200429 tasks = [
Victor Stinner337e03f2014-08-11 01:11:13 +0200430 asyncio.async(factorial("A", 2)),
431 asyncio.async(factorial("B", 3)),
432 asyncio.async(factorial("C", 4))]
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100433 loop.run_until_complete(asyncio.wait(tasks))
Victor Stinnerf40c6632014-01-28 23:32:40 +0100434 loop.close()
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100435
436Output::
437
Victor Stinner34f29462013-12-10 02:51:05 +0100438 Task A: Compute factorial(2)...
439 Task B: Compute factorial(2)...
440 Task C: Compute factorial(2)...
441 Task A: factorial(2) = 2
442 Task B: Compute factorial(3)...
443 Task C: Compute factorial(3)...
444 Task B: factorial(3) = 6
445 Task C: Compute factorial(4)...
446 Task C: factorial(4) = 24
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100447
Victor Stinner34f29462013-12-10 02:51:05 +0100448A task is automatically scheduled for execution when it is created. The event
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100449loop stops when all tasks are done.
450
451
Victor Stinnerea3183f2013-12-03 01:08:00 +0100452Task functions
453--------------
454
Eli Bendersky029981b2014-01-20 07:02:22 -0800455.. note::
456
457 In the functions below, the optional *loop* argument allows to explicitly set
458 the event loop object used by the underlying task or coroutine. If it's
459 not provided, the default event loop is used.
460
Victor Stinner99c2ab42013-12-03 19:17:25 +0100461.. function:: as_completed(fs, \*, loop=None, timeout=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100462
Victor Stinner99c2ab42013-12-03 19:17:25 +0100463 Return an iterator whose values, when waited for, are :class:`Future`
464 instances.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100465
Victor Stinner28d0ae482014-05-29 00:04:57 +0200466 Raises :exc:`asyncio.TimeoutError` if the timeout occurs before all Futures
467 are done.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100468
469 Example::
470
471 for f in as_completed(fs):
472 result = yield from f # The 'yield from' may raise
473 # Use result
474
475 .. note::
476
477 The futures ``f`` are not necessarily members of fs.
478
Victor Stinner99c2ab42013-12-03 19:17:25 +0100479.. function:: async(coro_or_future, \*, loop=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100480
Victor Stinner980dd842014-10-12 21:36:17 +0200481 Schedule the execution of a :ref:`coroutine object <coroutine>`: wrap it in
482 a future. Return a :class:`Task` object.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100483
Victor Stinner99c2ab42013-12-03 19:17:25 +0100484 If the argument is a :class:`Future`, it is returned directly.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100485
Victor Stinner337e03f2014-08-11 01:11:13 +0200486 .. seealso::
487
488 The :meth:`BaseEventLoop.create_task` method.
489
Victor Stinner99c2ab42013-12-03 19:17:25 +0100490.. function:: gather(\*coros_or_futures, loop=None, return_exceptions=False)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100491
Victor Stinner59759ff2014-01-16 19:30:21 +0100492 Return a future aggregating results from the given coroutine objects or
493 futures.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100494
495 All futures must share the same event loop. If all the tasks are done
496 successfully, the returned future's result is the list of results (in the
497 order of the original sequence, not necessarily the order of results
Victor Stinner12c68b22014-02-09 01:35:24 +0100498 arrival). If *return_exceptions* is True, exceptions in the tasks are
Victor Stinnerea3183f2013-12-03 01:08:00 +0100499 treated the same as successful results, and gathered in the result list;
500 otherwise, the first raised exception will be immediately propagated to the
501 returned future.
502
503 Cancellation: if the outer Future is cancelled, all children (that have not
504 completed yet) are also cancelled. If any child is cancelled, this is
505 treated as if it raised :exc:`~concurrent.futures.CancelledError` -- the
506 outer Future is *not* cancelled in this case. (This is to prevent the
507 cancellation of one child to cause other children to be cancelled.)
508
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100509.. function:: iscoroutine(obj)
510
511 Return ``True`` if *obj* is a :ref:`coroutine object <coroutine>`.
512
513.. function:: iscoroutinefunction(obj)
514
515 Return ``True`` if *func* is a decorated :ref:`coroutine function
516 <coroutine>`.
517
Victor Stinnerea3183f2013-12-03 01:08:00 +0100518.. function:: sleep(delay, result=None, \*, loop=None)
519
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500520 Create a :ref:`coroutine <coroutine>` that completes after a given
Eli Bendersky2d26af82014-01-20 06:59:23 -0800521 time (in seconds). If *result* is provided, it is produced to the caller
522 when the coroutine completes.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100523
Victor Stinner45b27ed2014-02-01 02:36:43 +0100524 The resolution of the sleep depends on the :ref:`granularity of the event
525 loop <asyncio-delayed-calls>`.
526
Victor Stinnerea3183f2013-12-03 01:08:00 +0100527.. function:: shield(arg, \*, loop=None)
528
529 Wait for a future, shielding it from cancellation.
530
531 The statement::
532
533 res = yield from shield(something())
534
535 is exactly equivalent to the statement::
536
537 res = yield from something()
538
539 *except* that if the coroutine containing it is cancelled, the task running
540 in ``something()`` is not cancelled. From the point of view of
541 ``something()``, the cancellation did not happen. But its caller is still
542 cancelled, so the yield-from expression still raises
543 :exc:`~concurrent.futures.CancelledError`. Note: If ``something()`` is
544 cancelled by other means this will still cancel ``shield()``.
545
546 If you want to completely ignore cancellation (not recommended) you can
547 combine ``shield()`` with a try/except clause, as follows::
548
549 try:
550 res = yield from shield(something())
551 except CancelledError:
552 res = None
553
Victor Stinner99c2ab42013-12-03 19:17:25 +0100554.. function:: wait(futures, \*, loop=None, timeout=None, return_when=ALL_COMPLETED)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100555
Victor Stinner59759ff2014-01-16 19:30:21 +0100556 Wait for the Futures and coroutine objects given by the sequence *futures*
557 to complete. Coroutines will be wrapped in Tasks. Returns two sets of
Victor Stinner99c2ab42013-12-03 19:17:25 +0100558 :class:`Future`: (done, pending).
Victor Stinnerea3183f2013-12-03 01:08:00 +0100559
Victor Stinnerdb74d982014-06-10 11:16:05 +0200560 The sequence *futures* must not be empty.
561
Victor Stinnerea3183f2013-12-03 01:08:00 +0100562 *timeout* can be used to control the maximum number of seconds to wait before
563 returning. *timeout* can be an int or float. If *timeout* is not specified
564 or ``None``, there is no limit to the wait time.
565
566 *return_when* indicates when this function should return. It must be one of
Victor Stinner933a8c82013-12-03 01:59:38 +0100567 the following constants of the :mod:`concurrent.futures` module:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100568
569 .. tabularcolumns:: |l|L|
570
571 +-----------------------------+----------------------------------------+
572 | Constant | Description |
573 +=============================+========================================+
574 | :const:`FIRST_COMPLETED` | The function will return when any |
575 | | future finishes or is cancelled. |
576 +-----------------------------+----------------------------------------+
577 | :const:`FIRST_EXCEPTION` | The function will return when any |
578 | | future finishes by raising an |
579 | | exception. If no future raises an |
580 | | exception then it is equivalent to |
581 | | :const:`ALL_COMPLETED`. |
582 +-----------------------------+----------------------------------------+
583 | :const:`ALL_COMPLETED` | The function will return when all |
584 | | futures finish or are cancelled. |
585 +-----------------------------+----------------------------------------+
586
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500587 This function is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100588
589 Usage::
590
591 done, pending = yield from asyncio.wait(fs)
592
593 .. note::
594
Victor Stinner28d0ae482014-05-29 00:04:57 +0200595 This does not raise :exc:`asyncio.TimeoutError`! Futures that aren't done
596 when the timeout occurs are returned in the second set.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100597
Victor Stinner3e09e322013-12-03 01:22:06 +0100598
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100599.. function:: wait_for(fut, timeout, \*, loop=None)
600
601 Wait for the single :class:`Future` or :ref:`coroutine object <coroutine>`
Victor Stinner530ef2f2014-07-08 12:39:10 +0200602 to complete with timeout. If *timeout* is ``None``, block until the future
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100603 completes.
604
Victor Stinner337e03f2014-08-11 01:11:13 +0200605 Coroutine will be wrapped in :class:`Task`.
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100606
607 Returns result of the Future or coroutine. When a timeout occurs, it
Victor Stinner28d0ae482014-05-29 00:04:57 +0200608 cancels the task and raises :exc:`asyncio.TimeoutError`. To avoid the task
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100609 cancellation, wrap it in :func:`shield`.
610
Victor Stinner530ef2f2014-07-08 12:39:10 +0200611 This function is a :ref:`coroutine <coroutine>`, usage::
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500612
Victor Stinner530ef2f2014-07-08 12:39:10 +0200613 result = yield from asyncio.wait_for(fut, 60.0)
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100614