blob: cde0e344179a4b2b8a60075eb93df7df4d3ce915 [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
101 :ref:`Hello World example using a callback <asyncio-hello-world-callback>`.
102
103
104Example: Chain coroutines
105^^^^^^^^^^^^^^^^^^^^^^^^^
106
107Example chaining coroutines::
108
109 import asyncio
110
111 @asyncio.coroutine
112 def compute(x, y):
113 print("Compute %s + %s ..." % (x, y))
114 yield from asyncio.sleep(1.0)
115 return x + y
116
117 @asyncio.coroutine
118 def print_sum(x, y):
119 result = yield from compute(x, y)
120 print("%s + %s = %s" % (x, y, result))
121
122 loop = asyncio.get_event_loop()
123 loop.run_until_complete(print_sum(1, 2))
Victor Stinnerf40c6632014-01-28 23:32:40 +0100124 loop.close()
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100125
126``compute()`` is chained to ``print_sum()``: ``print_sum()`` coroutine waits
Brian Curtina1afeec2014-02-08 18:36:14 -0600127until ``compute()`` is completed before returning its result.
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100128
Victor Stinner1c4b8922013-12-12 12:35:17 +0100129Sequence diagram of the example:
130
131.. image:: tulip_coro.png
132 :align: center
133
Victor Stinner86e139a2013-12-13 12:51:24 +0100134The "Task" is created by the :meth:`BaseEventLoop.run_until_complete` method
Victor Stinner59759ff2014-01-16 19:30:21 +0100135when it gets a coroutine object instead of a task.
Victor Stinner86e139a2013-12-13 12:51:24 +0100136
137The diagram shows the control flow, it does not describe exactly how things
138work internally. For example, the sleep coroutine creates an internal future
139which uses :meth:`BaseEventLoop.call_later` to wake up the task in 1 second.
Victor Stinner1c4b8922013-12-12 12:35:17 +0100140
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100141
Victor Stinner99c2ab42013-12-03 19:17:25 +0100142InvalidStateError
143-----------------
144
145.. exception:: InvalidStateError
146
147 The operation is not allowed in this state.
148
149
Victor Stinner28d0ae482014-05-29 00:04:57 +0200150TimeoutError
151------------
152
153.. exception:: TimeoutError
154
155 The operation exceeded the given deadline.
156
157.. note::
158
159 This exception is different from the builtin :exc:`TimeoutError` exception!
160
161
Victor Stinner99c2ab42013-12-03 19:17:25 +0100162Future
163------
164
165.. class:: Future(\*, loop=None)
166
167 This class is *almost* compatible with :class:`concurrent.futures.Future`.
168
169 Differences:
170
171 - :meth:`result` and :meth:`exception` do not take a timeout argument and
172 raise an exception when the future isn't done yet.
173
174 - Callbacks registered with :meth:`add_done_callback` are always called
175 via the event loop's :meth:`~BaseEventLoop.call_soon_threadsafe`.
176
177 - This class is not compatible with the :func:`~concurrent.futures.wait` and
178 :func:`~concurrent.futures.as_completed` functions in the
179 :mod:`concurrent.futures` package.
180
181 .. method:: cancel()
182
183 Cancel the future and schedule callbacks.
184
185 If the future is already done or cancelled, return ``False``. Otherwise,
186 change the future's state to cancelled, schedule the callbacks and return
187 ``True``.
188
189 .. method:: cancelled()
190
191 Return ``True`` if the future was cancelled.
192
193 .. method:: done()
194
195 Return True if the future is done.
196
197 Done means either that a result / exception are available, or that the
198 future was cancelled.
199
200 .. method:: result()
201
202 Return the result this future represents.
203
204 If the future has been cancelled, raises :exc:`CancelledError`. If the
205 future's result isn't yet available, raises :exc:`InvalidStateError`. If
206 the future is done and has an exception set, this exception is raised.
207
208 .. method:: exception()
209
210 Return the exception that was set on this future.
211
212 The exception (or ``None`` if no exception was set) is returned only if
213 the future is done. If the future has been cancelled, raises
214 :exc:`CancelledError`. If the future isn't done yet, raises
215 :exc:`InvalidStateError`.
216
217 .. method:: add_done_callback(fn)
218
219 Add a callback to be run when the future becomes done.
220
221 The callback is called with a single argument - the future object. If the
222 future is already done when this is called, the callback is scheduled
223 with :meth:`~BaseEventLoop.call_soon`.
224
225 .. method:: remove_done_callback(fn)
226
227 Remove all instances of a callback from the "call when done" list.
228
229 Returns the number of callbacks removed.
230
231 .. method:: set_result(result)
232
233 Mark the future done and set its result.
234
235 If the future is already done when this method is called, raises
236 :exc:`InvalidStateError`.
237
238 .. method:: set_exception(exception)
239
240 Mark the future done and set an exception.
241
242 If the future is already done when this method is called, raises
243 :exc:`InvalidStateError`.
244
245
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100246Example: Future with run_until_complete()
247^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
248
Victor Stinner59759ff2014-01-16 19:30:21 +0100249Example combining a :class:`Future` and a :ref:`coroutine function
250<coroutine>`::
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100251
252 import asyncio
253
254 @asyncio.coroutine
255 def slow_operation(future):
256 yield from asyncio.sleep(1)
Victor Stinner04e05da2014-02-17 10:54:30 +0100257 future.set_result('Future is done!')
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100258
259 loop = asyncio.get_event_loop()
260 future = asyncio.Future()
Victor Stinner337e03f2014-08-11 01:11:13 +0200261 asyncio.async(slow_operation(future))
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100262 loop.run_until_complete(future)
263 print(future.result())
Victor Stinnerf40c6632014-01-28 23:32:40 +0100264 loop.close()
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100265
Terry Jan Reedyc935a952014-07-24 02:33:14 -0400266The coroutine function is responsible for the computation (which takes 1 second)
Victor Stinner59759ff2014-01-16 19:30:21 +0100267and it stores the result into the future. The
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100268:meth:`~BaseEventLoop.run_until_complete` method waits for the completion of
269the future.
270
271.. note::
272 The :meth:`~BaseEventLoop.run_until_complete` method uses internally the
273 :meth:`~Future.add_done_callback` method to be notified when the future is
274 done.
275
276
277Example: Future with run_forever()
278^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
279
280The previous example can be written differently using the
281:meth:`Future.add_done_callback` method to describe explicitly the control
282flow::
283
284 import asyncio
285
286 @asyncio.coroutine
287 def slow_operation(future):
288 yield from asyncio.sleep(1)
Victor Stinner04e05da2014-02-17 10:54:30 +0100289 future.set_result('Future is done!')
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100290
291 def got_result(future):
292 print(future.result())
293 loop.stop()
294
295 loop = asyncio.get_event_loop()
296 future = asyncio.Future()
Victor Stinner337e03f2014-08-11 01:11:13 +0200297 asyncio.async(slow_operation(future))
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100298 future.add_done_callback(got_result)
Victor Stinner04e05da2014-02-17 10:54:30 +0100299 try:
300 loop.run_forever()
301 finally:
302 loop.close()
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100303
304In this example, the future is responsible to display the result and to stop
305the loop.
306
307.. note::
Victor Stinner59759ff2014-01-16 19:30:21 +0100308 The "slow_operation" coroutine object is only executed when the event loop
309 starts running, so it is possible to add a "done callback" to the future
310 after creating the task scheduling the coroutine object.
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100311
312
313
Victor Stinnerea3183f2013-12-03 01:08:00 +0100314Task
315----
316
317.. class:: Task(coro, \*, loop=None)
318
Victor Stinner530ef2f2014-07-08 12:39:10 +0200319 Schedule the execution of a :ref:`coroutine <coroutine>`: wrap it in a
320 future. A task is a subclass of :class:`Future`.
321
322 A task is responsible to execute a coroutine object in an event loop. If
323 the wrapped coroutine yields from a future, the task suspends the execution
324 of the wrapped coroutine and waits for the completition of the future. When
325 the future is done, the execution of the wrapped coroutine restarts with the
326 result or the exception of the future.
327
328 Event loops use cooperative scheduling: an event loop only runs one task at
329 the same time. Other tasks may run in parallel if other event loops are
330 running in different threads. While a task waits for the completion of a
331 future, the event loop executes a new task.
332
333 The cancellation of a task is different than cancelling a future. Calling
334 :meth:`cancel` will throw a :exc:`~concurrent.futures.CancelledError` to the
335 wrapped coroutine. :meth:`~Future.cancelled` only returns ``True`` if the
336 wrapped coroutine did not catch the
337 :exc:`~concurrent.futures.CancelledError` exception, or raised a
338 :exc:`~concurrent.futures.CancelledError` exception.
339
340 If a pending task is destroyed, the execution of its wrapped :ref:`coroutine
341 <coroutine>` did not complete. It is probably a bug and a warning is
342 logged: see :ref:`Pending task destroyed <asyncio-pending-task-destroyed>`.
343
Victor Stinner337e03f2014-08-11 01:11:13 +0200344 Don't create directly :class:`Task` instances: use the :func:`async`
345 function or the :meth:`BaseEventLoop.create_task` method.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100346
347 .. classmethod:: all_tasks(loop=None)
348
349 Return a set of all tasks for an event loop.
350
351 By default all tasks for the current event loop are returned.
352
Victor Stinner742520b2013-12-10 12:14:50 +0100353 .. classmethod:: current_task(loop=None)
354
355 Return the currently running task in an event loop or ``None``.
356
357 By default the current task for the current event loop is returned.
358
359 ``None`` is returned when called not in the context of a :class:`Task`.
360
Victor Stinner8d213572014-06-02 23:06:46 +0200361 .. method:: cancel()
362
363 Request this task to cancel itself.
364
365 This arranges for a :exc:`~concurrent.futures.CancelledError` to be
366 thrown into the wrapped coroutine on the next cycle through the event
367 loop. The coroutine then has a chance to clean up or even deny the
368 request using try/except/finally.
369
370 Contrary to :meth:`Future.cancel`, this does not guarantee that the task
371 will be cancelled: the exception might be caught and acted upon, delaying
372 cancellation of the task or preventing it completely. The task may also
373 return a value or raise a different exception.
374
375 Immediately after this method is called, :meth:`~Future.cancelled` will
376 not return ``True`` (unless the task was already cancelled). A task will
377 be marked as cancelled when the wrapped coroutine terminates with a
378 :exc:`~concurrent.futures.CancelledError` exception (even if
379 :meth:`cancel` was not called).
380
381 .. method:: get_stack(\*, limit=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100382
383 Return the list of stack frames for this task's coroutine.
384
385 If the coroutine is active, this returns the stack where it is suspended.
386 If the coroutine has completed successfully or was cancelled, this
387 returns an empty list. If the coroutine was terminated by an exception,
388 this returns the list of traceback frames.
389
390 The frames are always ordered from oldest to newest.
391
Brian Curtina1afeec2014-02-08 18:36:14 -0600392 The optional limit gives the maximum number of frames to return; by
Victor Stinnerea3183f2013-12-03 01:08:00 +0100393 default all available frames are returned. Its meaning differs depending
394 on whether a stack or a traceback is returned: the newest frames of a
395 stack are returned, but the oldest frames of a traceback are returned.
396 (This matches the behavior of the traceback module.)
397
398 For reasons beyond our control, only one stack frame is returned for a
399 suspended coroutine.
400
401 .. method:: print_stack(\*, limit=None, file=None)
402
403 Print the stack or traceback for this task's coroutine.
404
405 This produces output similar to that of the traceback module, for the
406 frames retrieved by get_stack(). The limit argument is passed to
407 get_stack(). The file argument is an I/O stream to which the output
408 goes; by default it goes to sys.stderr.
409
410
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100411Example: Parallel execution of tasks
412^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
413
414Example executing 3 tasks (A, B, C) in parallel::
415
416 import asyncio
417
418 @asyncio.coroutine
Victor Stinner34f29462013-12-10 02:51:05 +0100419 def factorial(name, number):
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100420 f = 1
Victor Stinner34f29462013-12-10 02:51:05 +0100421 for i in range(2, number+1):
422 print("Task %s: Compute factorial(%s)..." % (name, i))
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100423 yield from asyncio.sleep(1)
Victor Stinner34f29462013-12-10 02:51:05 +0100424 f *= i
425 print("Task %s: factorial(%s) = %s" % (name, number, f))
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100426
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100427 loop = asyncio.get_event_loop()
Victor Stinner530ef2f2014-07-08 12:39:10 +0200428 tasks = [
Victor Stinner337e03f2014-08-11 01:11:13 +0200429 asyncio.async(factorial("A", 2)),
430 asyncio.async(factorial("B", 3)),
431 asyncio.async(factorial("C", 4))]
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100432 loop.run_until_complete(asyncio.wait(tasks))
Victor Stinnerf40c6632014-01-28 23:32:40 +0100433 loop.close()
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100434
435Output::
436
Victor Stinner34f29462013-12-10 02:51:05 +0100437 Task A: Compute factorial(2)...
438 Task B: Compute factorial(2)...
439 Task C: Compute factorial(2)...
440 Task A: factorial(2) = 2
441 Task B: Compute factorial(3)...
442 Task C: Compute factorial(3)...
443 Task B: factorial(3) = 6
444 Task C: Compute factorial(4)...
445 Task C: factorial(4) = 24
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100446
Victor Stinner34f29462013-12-10 02:51:05 +0100447A task is automatically scheduled for execution when it is created. The event
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100448loop stops when all tasks are done.
449
450
Victor Stinnerea3183f2013-12-03 01:08:00 +0100451Task functions
452--------------
453
Eli Bendersky029981b2014-01-20 07:02:22 -0800454.. note::
455
456 In the functions below, the optional *loop* argument allows to explicitly set
457 the event loop object used by the underlying task or coroutine. If it's
458 not provided, the default event loop is used.
459
Victor Stinner99c2ab42013-12-03 19:17:25 +0100460.. function:: as_completed(fs, \*, loop=None, timeout=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100461
Victor Stinner99c2ab42013-12-03 19:17:25 +0100462 Return an iterator whose values, when waited for, are :class:`Future`
463 instances.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100464
Victor Stinner28d0ae482014-05-29 00:04:57 +0200465 Raises :exc:`asyncio.TimeoutError` if the timeout occurs before all Futures
466 are done.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100467
468 Example::
469
470 for f in as_completed(fs):
471 result = yield from f # The 'yield from' may raise
472 # Use result
473
474 .. note::
475
476 The futures ``f`` are not necessarily members of fs.
477
Victor Stinner99c2ab42013-12-03 19:17:25 +0100478.. function:: async(coro_or_future, \*, loop=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100479
Victor Stinner337e03f2014-08-11 01:11:13 +0200480 Wrap a :ref:`coroutine object <coroutine>` in a future.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100481
Victor Stinner99c2ab42013-12-03 19:17:25 +0100482 If the argument is a :class:`Future`, it is returned directly.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100483
Victor Stinner337e03f2014-08-11 01:11:13 +0200484 .. seealso::
485
486 The :meth:`BaseEventLoop.create_task` method.
487
Victor Stinner99c2ab42013-12-03 19:17:25 +0100488.. function:: gather(\*coros_or_futures, loop=None, return_exceptions=False)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100489
Victor Stinner59759ff2014-01-16 19:30:21 +0100490 Return a future aggregating results from the given coroutine objects or
491 futures.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100492
493 All futures must share the same event loop. If all the tasks are done
494 successfully, the returned future's result is the list of results (in the
495 order of the original sequence, not necessarily the order of results
Victor Stinner12c68b22014-02-09 01:35:24 +0100496 arrival). If *return_exceptions* is True, exceptions in the tasks are
Victor Stinnerea3183f2013-12-03 01:08:00 +0100497 treated the same as successful results, and gathered in the result list;
498 otherwise, the first raised exception will be immediately propagated to the
499 returned future.
500
501 Cancellation: if the outer Future is cancelled, all children (that have not
502 completed yet) are also cancelled. If any child is cancelled, this is
503 treated as if it raised :exc:`~concurrent.futures.CancelledError` -- the
504 outer Future is *not* cancelled in this case. (This is to prevent the
505 cancellation of one child to cause other children to be cancelled.)
506
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100507.. function:: iscoroutine(obj)
508
509 Return ``True`` if *obj* is a :ref:`coroutine object <coroutine>`.
510
511.. function:: iscoroutinefunction(obj)
512
513 Return ``True`` if *func* is a decorated :ref:`coroutine function
514 <coroutine>`.
515
Victor Stinnerea3183f2013-12-03 01:08:00 +0100516.. function:: sleep(delay, result=None, \*, loop=None)
517
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500518 Create a :ref:`coroutine <coroutine>` that completes after a given
Eli Bendersky2d26af82014-01-20 06:59:23 -0800519 time (in seconds). If *result* is provided, it is produced to the caller
520 when the coroutine completes.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100521
Victor Stinner45b27ed2014-02-01 02:36:43 +0100522 The resolution of the sleep depends on the :ref:`granularity of the event
523 loop <asyncio-delayed-calls>`.
524
Victor Stinnerea3183f2013-12-03 01:08:00 +0100525.. function:: shield(arg, \*, loop=None)
526
527 Wait for a future, shielding it from cancellation.
528
529 The statement::
530
531 res = yield from shield(something())
532
533 is exactly equivalent to the statement::
534
535 res = yield from something()
536
537 *except* that if the coroutine containing it is cancelled, the task running
538 in ``something()`` is not cancelled. From the point of view of
539 ``something()``, the cancellation did not happen. But its caller is still
540 cancelled, so the yield-from expression still raises
541 :exc:`~concurrent.futures.CancelledError`. Note: If ``something()`` is
542 cancelled by other means this will still cancel ``shield()``.
543
544 If you want to completely ignore cancellation (not recommended) you can
545 combine ``shield()`` with a try/except clause, as follows::
546
547 try:
548 res = yield from shield(something())
549 except CancelledError:
550 res = None
551
Victor Stinner99c2ab42013-12-03 19:17:25 +0100552.. function:: wait(futures, \*, loop=None, timeout=None, return_when=ALL_COMPLETED)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100553
Victor Stinner59759ff2014-01-16 19:30:21 +0100554 Wait for the Futures and coroutine objects given by the sequence *futures*
555 to complete. Coroutines will be wrapped in Tasks. Returns two sets of
Victor Stinner99c2ab42013-12-03 19:17:25 +0100556 :class:`Future`: (done, pending).
Victor Stinnerea3183f2013-12-03 01:08:00 +0100557
Victor Stinnerdb74d982014-06-10 11:16:05 +0200558 The sequence *futures* must not be empty.
559
Victor Stinnerea3183f2013-12-03 01:08:00 +0100560 *timeout* can be used to control the maximum number of seconds to wait before
561 returning. *timeout* can be an int or float. If *timeout* is not specified
562 or ``None``, there is no limit to the wait time.
563
564 *return_when* indicates when this function should return. It must be one of
Victor Stinner933a8c82013-12-03 01:59:38 +0100565 the following constants of the :mod:`concurrent.futures` module:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100566
567 .. tabularcolumns:: |l|L|
568
569 +-----------------------------+----------------------------------------+
570 | Constant | Description |
571 +=============================+========================================+
572 | :const:`FIRST_COMPLETED` | The function will return when any |
573 | | future finishes or is cancelled. |
574 +-----------------------------+----------------------------------------+
575 | :const:`FIRST_EXCEPTION` | The function will return when any |
576 | | future finishes by raising an |
577 | | exception. If no future raises an |
578 | | exception then it is equivalent to |
579 | | :const:`ALL_COMPLETED`. |
580 +-----------------------------+----------------------------------------+
581 | :const:`ALL_COMPLETED` | The function will return when all |
582 | | futures finish or are cancelled. |
583 +-----------------------------+----------------------------------------+
584
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500585 This function is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100586
587 Usage::
588
589 done, pending = yield from asyncio.wait(fs)
590
591 .. note::
592
Victor Stinner28d0ae482014-05-29 00:04:57 +0200593 This does not raise :exc:`asyncio.TimeoutError`! Futures that aren't done
594 when the timeout occurs are returned in the second set.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100595
Victor Stinner3e09e322013-12-03 01:22:06 +0100596
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100597.. function:: wait_for(fut, timeout, \*, loop=None)
598
599 Wait for the single :class:`Future` or :ref:`coroutine object <coroutine>`
Victor Stinner530ef2f2014-07-08 12:39:10 +0200600 to complete with timeout. If *timeout* is ``None``, block until the future
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100601 completes.
602
Victor Stinner337e03f2014-08-11 01:11:13 +0200603 Coroutine will be wrapped in :class:`Task`.
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100604
605 Returns result of the Future or coroutine. When a timeout occurs, it
Victor Stinner28d0ae482014-05-29 00:04:57 +0200606 cancels the task and raises :exc:`asyncio.TimeoutError`. To avoid the task
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100607 cancellation, wrap it in :func:`shield`.
608
Victor Stinner530ef2f2014-07-08 12:39:10 +0200609 This function is a :ref:`coroutine <coroutine>`, usage::
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500610
Victor Stinner530ef2f2014-07-08 12:39:10 +0200611 result = yield from asyncio.wait_for(fut, 60.0)
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100612