blob: f1894daf31ea470ff04e3f6ecd670d0678fcf6e3 [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
54(assuming the other coroutine is already running!), or convert it to a
55:class:`Task`.
56
57Coroutines (and tasks) can only run when the event loop is running.
58
Victor Stinnerdb39a0d2014-01-16 18:58:01 +010059.. decorator:: coroutine
60
61 Decorator to mark coroutines.
62
63 If the coroutine is not yielded from before it is destroyed, an error
64 message is logged. See :ref:`Detect coroutines never scheduled
65 <asyncio-coroutine-not-scheduled>`.
66
Yury Selivanov37f15bc2014-02-20 16:20:44 -050067.. note::
68
69 In this documentation, some methods are documented as coroutines,
70 even if they are plain Python functions returning a :class:`Future`.
71 This is intentional to have a freedom of tweaking the implementation
72 of these functions in the future. If such a function is needed to be
73 used in a callback-style code, wrap its result with :func:`async`.
74
Victor Stinnerea3183f2013-12-03 01:08:00 +010075
Victor Stinnerb69d62d2013-12-10 02:09:46 +010076.. _asyncio-hello-world-coroutine:
77
78Example: "Hello World" coroutine
79^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
80
81Print ``"Hello World"`` every two seconds using a coroutine::
82
83 import asyncio
84
85 @asyncio.coroutine
86 def greet_every_two_seconds():
87 while True:
88 print('Hello World')
89 yield from asyncio.sleep(2)
90
91 loop = asyncio.get_event_loop()
92 loop.run_until_complete(greet_every_two_seconds())
93
Victor Stinnerb69d62d2013-12-10 02:09:46 +010094.. seealso::
95
96 :ref:`Hello World example using a callback <asyncio-hello-world-callback>`.
97
98
99Example: Chain coroutines
100^^^^^^^^^^^^^^^^^^^^^^^^^
101
102Example chaining coroutines::
103
104 import asyncio
105
106 @asyncio.coroutine
107 def compute(x, y):
108 print("Compute %s + %s ..." % (x, y))
109 yield from asyncio.sleep(1.0)
110 return x + y
111
112 @asyncio.coroutine
113 def print_sum(x, y):
114 result = yield from compute(x, y)
115 print("%s + %s = %s" % (x, y, result))
116
117 loop = asyncio.get_event_loop()
118 loop.run_until_complete(print_sum(1, 2))
Victor Stinnerf40c6632014-01-28 23:32:40 +0100119 loop.close()
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100120
121``compute()`` is chained to ``print_sum()``: ``print_sum()`` coroutine waits
Brian Curtina1afeec2014-02-08 18:36:14 -0600122until ``compute()`` is completed before returning its result.
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100123
Victor Stinner1c4b8922013-12-12 12:35:17 +0100124Sequence diagram of the example:
125
126.. image:: tulip_coro.png
127 :align: center
128
Victor Stinner86e139a2013-12-13 12:51:24 +0100129The "Task" is created by the :meth:`BaseEventLoop.run_until_complete` method
Victor Stinner59759ff2014-01-16 19:30:21 +0100130when it gets a coroutine object instead of a task.
Victor Stinner86e139a2013-12-13 12:51:24 +0100131
132The diagram shows the control flow, it does not describe exactly how things
133work internally. For example, the sleep coroutine creates an internal future
134which uses :meth:`BaseEventLoop.call_later` to wake up the task in 1 second.
Victor Stinner1c4b8922013-12-12 12:35:17 +0100135
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100136
Victor Stinner99c2ab42013-12-03 19:17:25 +0100137InvalidStateError
138-----------------
139
140.. exception:: InvalidStateError
141
142 The operation is not allowed in this state.
143
144
Victor Stinner28d0ae482014-05-29 00:04:57 +0200145TimeoutError
146------------
147
148.. exception:: TimeoutError
149
150 The operation exceeded the given deadline.
151
152.. note::
153
154 This exception is different from the builtin :exc:`TimeoutError` exception!
155
156
Victor Stinner99c2ab42013-12-03 19:17:25 +0100157Future
158------
159
160.. class:: Future(\*, loop=None)
161
162 This class is *almost* compatible with :class:`concurrent.futures.Future`.
163
164 Differences:
165
166 - :meth:`result` and :meth:`exception` do not take a timeout argument and
167 raise an exception when the future isn't done yet.
168
169 - Callbacks registered with :meth:`add_done_callback` are always called
170 via the event loop's :meth:`~BaseEventLoop.call_soon_threadsafe`.
171
172 - This class is not compatible with the :func:`~concurrent.futures.wait` and
173 :func:`~concurrent.futures.as_completed` functions in the
174 :mod:`concurrent.futures` package.
175
176 .. method:: cancel()
177
178 Cancel the future and schedule callbacks.
179
180 If the future is already done or cancelled, return ``False``. Otherwise,
181 change the future's state to cancelled, schedule the callbacks and return
182 ``True``.
183
184 .. method:: cancelled()
185
186 Return ``True`` if the future was cancelled.
187
188 .. method:: done()
189
190 Return True if the future is done.
191
192 Done means either that a result / exception are available, or that the
193 future was cancelled.
194
195 .. method:: result()
196
197 Return the result this future represents.
198
199 If the future has been cancelled, raises :exc:`CancelledError`. If the
200 future's result isn't yet available, raises :exc:`InvalidStateError`. If
201 the future is done and has an exception set, this exception is raised.
202
203 .. method:: exception()
204
205 Return the exception that was set on this future.
206
207 The exception (or ``None`` if no exception was set) is returned only if
208 the future is done. If the future has been cancelled, raises
209 :exc:`CancelledError`. If the future isn't done yet, raises
210 :exc:`InvalidStateError`.
211
212 .. method:: add_done_callback(fn)
213
214 Add a callback to be run when the future becomes done.
215
216 The callback is called with a single argument - the future object. If the
217 future is already done when this is called, the callback is scheduled
218 with :meth:`~BaseEventLoop.call_soon`.
219
220 .. method:: remove_done_callback(fn)
221
222 Remove all instances of a callback from the "call when done" list.
223
224 Returns the number of callbacks removed.
225
226 .. method:: set_result(result)
227
228 Mark the future done and set its result.
229
230 If the future is already done when this method is called, raises
231 :exc:`InvalidStateError`.
232
233 .. method:: set_exception(exception)
234
235 Mark the future done and set an exception.
236
237 If the future is already done when this method is called, raises
238 :exc:`InvalidStateError`.
239
240
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100241Example: Future with run_until_complete()
242^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
243
Victor Stinner59759ff2014-01-16 19:30:21 +0100244Example combining a :class:`Future` and a :ref:`coroutine function
245<coroutine>`::
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100246
247 import asyncio
248
249 @asyncio.coroutine
250 def slow_operation(future):
251 yield from asyncio.sleep(1)
Victor Stinner04e05da2014-02-17 10:54:30 +0100252 future.set_result('Future is done!')
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100253
254 loop = asyncio.get_event_loop()
255 future = asyncio.Future()
256 asyncio.Task(slow_operation(future))
257 loop.run_until_complete(future)
258 print(future.result())
Victor Stinnerf40c6632014-01-28 23:32:40 +0100259 loop.close()
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100260
Victor Stinner59759ff2014-01-16 19:30:21 +0100261The coroutine function is responsible of the computation (which takes 1 second)
262and it stores the result into the future. The
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100263:meth:`~BaseEventLoop.run_until_complete` method waits for the completion of
264the future.
265
266.. note::
267 The :meth:`~BaseEventLoop.run_until_complete` method uses internally the
268 :meth:`~Future.add_done_callback` method to be notified when the future is
269 done.
270
271
272Example: Future with run_forever()
273^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
274
275The previous example can be written differently using the
276:meth:`Future.add_done_callback` method to describe explicitly the control
277flow::
278
279 import asyncio
280
281 @asyncio.coroutine
282 def slow_operation(future):
283 yield from asyncio.sleep(1)
Victor Stinner04e05da2014-02-17 10:54:30 +0100284 future.set_result('Future is done!')
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100285
286 def got_result(future):
287 print(future.result())
288 loop.stop()
289
290 loop = asyncio.get_event_loop()
291 future = asyncio.Future()
292 asyncio.Task(slow_operation(future))
293 future.add_done_callback(got_result)
Victor Stinner04e05da2014-02-17 10:54:30 +0100294 try:
295 loop.run_forever()
296 finally:
297 loop.close()
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100298
299In this example, the future is responsible to display the result and to stop
300the loop.
301
302.. note::
Victor Stinner59759ff2014-01-16 19:30:21 +0100303 The "slow_operation" coroutine object is only executed when the event loop
304 starts running, so it is possible to add a "done callback" to the future
305 after creating the task scheduling the coroutine object.
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100306
307
308
Victor Stinnerea3183f2013-12-03 01:08:00 +0100309Task
310----
311
312.. class:: Task(coro, \*, loop=None)
313
Victor Stinner59759ff2014-01-16 19:30:21 +0100314 A coroutine object wrapped in a :class:`Future`. Subclass of :class:`Future`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100315
316 .. classmethod:: all_tasks(loop=None)
317
318 Return a set of all tasks for an event loop.
319
320 By default all tasks for the current event loop are returned.
321
Victor Stinner742520b2013-12-10 12:14:50 +0100322 .. classmethod:: current_task(loop=None)
323
324 Return the currently running task in an event loop or ``None``.
325
326 By default the current task for the current event loop is returned.
327
328 ``None`` is returned when called not in the context of a :class:`Task`.
329
Victor Stinner8d213572014-06-02 23:06:46 +0200330 .. method:: cancel()
331
332 Request this task to cancel itself.
333
334 This arranges for a :exc:`~concurrent.futures.CancelledError` to be
335 thrown into the wrapped coroutine on the next cycle through the event
336 loop. The coroutine then has a chance to clean up or even deny the
337 request using try/except/finally.
338
339 Contrary to :meth:`Future.cancel`, this does not guarantee that the task
340 will be cancelled: the exception might be caught and acted upon, delaying
341 cancellation of the task or preventing it completely. The task may also
342 return a value or raise a different exception.
343
344 Immediately after this method is called, :meth:`~Future.cancelled` will
345 not return ``True`` (unless the task was already cancelled). A task will
346 be marked as cancelled when the wrapped coroutine terminates with a
347 :exc:`~concurrent.futures.CancelledError` exception (even if
348 :meth:`cancel` was not called).
349
350 .. method:: get_stack(\*, limit=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100351
352 Return the list of stack frames for this task's coroutine.
353
354 If the coroutine is active, this returns the stack where it is suspended.
355 If the coroutine has completed successfully or was cancelled, this
356 returns an empty list. If the coroutine was terminated by an exception,
357 this returns the list of traceback frames.
358
359 The frames are always ordered from oldest to newest.
360
Brian Curtina1afeec2014-02-08 18:36:14 -0600361 The optional limit gives the maximum number of frames to return; by
Victor Stinnerea3183f2013-12-03 01:08:00 +0100362 default all available frames are returned. Its meaning differs depending
363 on whether a stack or a traceback is returned: the newest frames of a
364 stack are returned, but the oldest frames of a traceback are returned.
365 (This matches the behavior of the traceback module.)
366
367 For reasons beyond our control, only one stack frame is returned for a
368 suspended coroutine.
369
370 .. method:: print_stack(\*, limit=None, file=None)
371
372 Print the stack or traceback for this task's coroutine.
373
374 This produces output similar to that of the traceback module, for the
375 frames retrieved by get_stack(). The limit argument is passed to
376 get_stack(). The file argument is an I/O stream to which the output
377 goes; by default it goes to sys.stderr.
378
379
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100380Example: Parallel execution of tasks
381^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
382
383Example executing 3 tasks (A, B, C) in parallel::
384
385 import asyncio
386
387 @asyncio.coroutine
Victor Stinner34f29462013-12-10 02:51:05 +0100388 def factorial(name, number):
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100389 f = 1
Victor Stinner34f29462013-12-10 02:51:05 +0100390 for i in range(2, number+1):
391 print("Task %s: Compute factorial(%s)..." % (name, i))
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100392 yield from asyncio.sleep(1)
Victor Stinner34f29462013-12-10 02:51:05 +0100393 f *= i
394 print("Task %s: factorial(%s) = %s" % (name, number, f))
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100395
Victor Stinnera6fa1532013-12-10 12:20:14 +0100396 tasks = [
397 asyncio.Task(factorial("A", 2)),
398 asyncio.Task(factorial("B", 3)),
399 asyncio.Task(factorial("C", 4))]
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100400
401 loop = asyncio.get_event_loop()
402 loop.run_until_complete(asyncio.wait(tasks))
Victor Stinnerf40c6632014-01-28 23:32:40 +0100403 loop.close()
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100404
405Output::
406
Victor Stinner34f29462013-12-10 02:51:05 +0100407 Task A: Compute factorial(2)...
408 Task B: Compute factorial(2)...
409 Task C: Compute factorial(2)...
410 Task A: factorial(2) = 2
411 Task B: Compute factorial(3)...
412 Task C: Compute factorial(3)...
413 Task B: factorial(3) = 6
414 Task C: Compute factorial(4)...
415 Task C: factorial(4) = 24
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100416
Victor Stinner34f29462013-12-10 02:51:05 +0100417A task is automatically scheduled for execution when it is created. The event
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100418loop stops when all tasks are done.
419
420
Victor Stinnerea3183f2013-12-03 01:08:00 +0100421Task functions
422--------------
423
Eli Bendersky029981b2014-01-20 07:02:22 -0800424.. note::
425
426 In the functions below, the optional *loop* argument allows to explicitly set
427 the event loop object used by the underlying task or coroutine. If it's
428 not provided, the default event loop is used.
429
Victor Stinner99c2ab42013-12-03 19:17:25 +0100430.. function:: as_completed(fs, \*, loop=None, timeout=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100431
Victor Stinner99c2ab42013-12-03 19:17:25 +0100432 Return an iterator whose values, when waited for, are :class:`Future`
433 instances.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100434
Victor Stinner28d0ae482014-05-29 00:04:57 +0200435 Raises :exc:`asyncio.TimeoutError` if the timeout occurs before all Futures
436 are done.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100437
438 Example::
439
440 for f in as_completed(fs):
441 result = yield from f # The 'yield from' may raise
442 # Use result
443
444 .. note::
445
446 The futures ``f`` are not necessarily members of fs.
447
Victor Stinner99c2ab42013-12-03 19:17:25 +0100448.. function:: async(coro_or_future, \*, loop=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100449
Victor Stinner59759ff2014-01-16 19:30:21 +0100450 Wrap a :ref:`coroutine object <coroutine>` in a future.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100451
Victor Stinner99c2ab42013-12-03 19:17:25 +0100452 If the argument is a :class:`Future`, it is returned directly.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100453
Victor Stinner99c2ab42013-12-03 19:17:25 +0100454.. function:: gather(\*coros_or_futures, loop=None, return_exceptions=False)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100455
Victor Stinner59759ff2014-01-16 19:30:21 +0100456 Return a future aggregating results from the given coroutine objects or
457 futures.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100458
459 All futures must share the same event loop. If all the tasks are done
460 successfully, the returned future's result is the list of results (in the
461 order of the original sequence, not necessarily the order of results
Victor Stinner12c68b22014-02-09 01:35:24 +0100462 arrival). If *return_exceptions* is True, exceptions in the tasks are
Victor Stinnerea3183f2013-12-03 01:08:00 +0100463 treated the same as successful results, and gathered in the result list;
464 otherwise, the first raised exception will be immediately propagated to the
465 returned future.
466
467 Cancellation: if the outer Future is cancelled, all children (that have not
468 completed yet) are also cancelled. If any child is cancelled, this is
469 treated as if it raised :exc:`~concurrent.futures.CancelledError` -- the
470 outer Future is *not* cancelled in this case. (This is to prevent the
471 cancellation of one child to cause other children to be cancelled.)
472
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100473.. function:: iscoroutine(obj)
474
475 Return ``True`` if *obj* is a :ref:`coroutine object <coroutine>`.
476
477.. function:: iscoroutinefunction(obj)
478
479 Return ``True`` if *func* is a decorated :ref:`coroutine function
480 <coroutine>`.
481
Victor Stinnerea3183f2013-12-03 01:08:00 +0100482.. function:: sleep(delay, result=None, \*, loop=None)
483
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500484 Create a :ref:`coroutine <coroutine>` that completes after a given
Eli Bendersky2d26af82014-01-20 06:59:23 -0800485 time (in seconds). If *result* is provided, it is produced to the caller
486 when the coroutine completes.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100487
Victor Stinner45b27ed2014-02-01 02:36:43 +0100488 The resolution of the sleep depends on the :ref:`granularity of the event
489 loop <asyncio-delayed-calls>`.
490
Victor Stinnerea3183f2013-12-03 01:08:00 +0100491.. function:: shield(arg, \*, loop=None)
492
493 Wait for a future, shielding it from cancellation.
494
495 The statement::
496
497 res = yield from shield(something())
498
499 is exactly equivalent to the statement::
500
501 res = yield from something()
502
503 *except* that if the coroutine containing it is cancelled, the task running
504 in ``something()`` is not cancelled. From the point of view of
505 ``something()``, the cancellation did not happen. But its caller is still
506 cancelled, so the yield-from expression still raises
507 :exc:`~concurrent.futures.CancelledError`. Note: If ``something()`` is
508 cancelled by other means this will still cancel ``shield()``.
509
510 If you want to completely ignore cancellation (not recommended) you can
511 combine ``shield()`` with a try/except clause, as follows::
512
513 try:
514 res = yield from shield(something())
515 except CancelledError:
516 res = None
517
Victor Stinner99c2ab42013-12-03 19:17:25 +0100518.. function:: wait(futures, \*, loop=None, timeout=None, return_when=ALL_COMPLETED)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100519
Victor Stinner59759ff2014-01-16 19:30:21 +0100520 Wait for the Futures and coroutine objects given by the sequence *futures*
521 to complete. Coroutines will be wrapped in Tasks. Returns two sets of
Victor Stinner99c2ab42013-12-03 19:17:25 +0100522 :class:`Future`: (done, pending).
Victor Stinnerea3183f2013-12-03 01:08:00 +0100523
Victor Stinnerdb74d982014-06-10 11:16:05 +0200524 The sequence *futures* must not be empty.
525
Victor Stinnerea3183f2013-12-03 01:08:00 +0100526 *timeout* can be used to control the maximum number of seconds to wait before
527 returning. *timeout* can be an int or float. If *timeout* is not specified
528 or ``None``, there is no limit to the wait time.
529
530 *return_when* indicates when this function should return. It must be one of
Victor Stinner933a8c82013-12-03 01:59:38 +0100531 the following constants of the :mod:`concurrent.futures` module:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100532
533 .. tabularcolumns:: |l|L|
534
535 +-----------------------------+----------------------------------------+
536 | Constant | Description |
537 +=============================+========================================+
538 | :const:`FIRST_COMPLETED` | The function will return when any |
539 | | future finishes or is cancelled. |
540 +-----------------------------+----------------------------------------+
541 | :const:`FIRST_EXCEPTION` | The function will return when any |
542 | | future finishes by raising an |
543 | | exception. If no future raises an |
544 | | exception then it is equivalent to |
545 | | :const:`ALL_COMPLETED`. |
546 +-----------------------------+----------------------------------------+
547 | :const:`ALL_COMPLETED` | The function will return when all |
548 | | futures finish or are cancelled. |
549 +-----------------------------+----------------------------------------+
550
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500551 This function is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100552
553 Usage::
554
555 done, pending = yield from asyncio.wait(fs)
556
557 .. note::
558
Victor Stinner28d0ae482014-05-29 00:04:57 +0200559 This does not raise :exc:`asyncio.TimeoutError`! Futures that aren't done
560 when the timeout occurs are returned in the second set.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100561
Victor Stinner3e09e322013-12-03 01:22:06 +0100562
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100563.. function:: wait_for(fut, timeout, \*, loop=None)
564
565 Wait for the single :class:`Future` or :ref:`coroutine object <coroutine>`
566 to complete, with timeout. If *timeout* is ``None``, block until the future
567 completes.
568
569 Coroutine will be wrapped in :class:`Task`.
570
571 Returns result of the Future or coroutine. When a timeout occurs, it
Victor Stinner28d0ae482014-05-29 00:04:57 +0200572 cancels the task and raises :exc:`asyncio.TimeoutError`. To avoid the task
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100573 cancellation, wrap it in :func:`shield`.
574
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500575 This function is a :ref:`coroutine <coroutine>`.
576
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100577 Usage::
578
579 result = yield from asyncio.wait_for(fut, 60.0)
580