blob: cfad0bc22bb7e13a80974ab6c74b49e3122cb4e5 [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
Victor Stinnerea3183f2013-12-03 01:08:00 +010067
Victor Stinnerb69d62d2013-12-10 02:09:46 +010068.. _asyncio-hello-world-coroutine:
69
70Example: "Hello World" coroutine
71^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
72
73Print ``"Hello World"`` every two seconds using a coroutine::
74
75 import asyncio
76
77 @asyncio.coroutine
78 def greet_every_two_seconds():
79 while True:
80 print('Hello World')
81 yield from asyncio.sleep(2)
82
83 loop = asyncio.get_event_loop()
84 loop.run_until_complete(greet_every_two_seconds())
85
Victor Stinnerb69d62d2013-12-10 02:09:46 +010086.. seealso::
87
88 :ref:`Hello World example using a callback <asyncio-hello-world-callback>`.
89
90
91Example: Chain coroutines
92^^^^^^^^^^^^^^^^^^^^^^^^^
93
94Example chaining coroutines::
95
96 import asyncio
97
98 @asyncio.coroutine
99 def compute(x, y):
100 print("Compute %s + %s ..." % (x, y))
101 yield from asyncio.sleep(1.0)
102 return x + y
103
104 @asyncio.coroutine
105 def print_sum(x, y):
106 result = yield from compute(x, y)
107 print("%s + %s = %s" % (x, y, result))
108
109 loop = asyncio.get_event_loop()
110 loop.run_until_complete(print_sum(1, 2))
Victor Stinnerf40c6632014-01-28 23:32:40 +0100111 loop.close()
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100112
113``compute()`` is chained to ``print_sum()``: ``print_sum()`` coroutine waits
114until ``compute()`` is completed before returing its result.
115
Victor Stinner1c4b8922013-12-12 12:35:17 +0100116Sequence diagram of the example:
117
118.. image:: tulip_coro.png
119 :align: center
120
Victor Stinner86e139a2013-12-13 12:51:24 +0100121The "Task" is created by the :meth:`BaseEventLoop.run_until_complete` method
Victor Stinner59759ff2014-01-16 19:30:21 +0100122when it gets a coroutine object instead of a task.
Victor Stinner86e139a2013-12-13 12:51:24 +0100123
124The diagram shows the control flow, it does not describe exactly how things
125work internally. For example, the sleep coroutine creates an internal future
126which uses :meth:`BaseEventLoop.call_later` to wake up the task in 1 second.
Victor Stinner1c4b8922013-12-12 12:35:17 +0100127
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100128
Victor Stinner99c2ab42013-12-03 19:17:25 +0100129InvalidStateError
130-----------------
131
132.. exception:: InvalidStateError
133
134 The operation is not allowed in this state.
135
136
137Future
138------
139
140.. class:: Future(\*, loop=None)
141
142 This class is *almost* compatible with :class:`concurrent.futures.Future`.
143
144 Differences:
145
146 - :meth:`result` and :meth:`exception` do not take a timeout argument and
147 raise an exception when the future isn't done yet.
148
149 - Callbacks registered with :meth:`add_done_callback` are always called
150 via the event loop's :meth:`~BaseEventLoop.call_soon_threadsafe`.
151
152 - This class is not compatible with the :func:`~concurrent.futures.wait` and
153 :func:`~concurrent.futures.as_completed` functions in the
154 :mod:`concurrent.futures` package.
155
156 .. method:: cancel()
157
158 Cancel the future and schedule callbacks.
159
160 If the future is already done or cancelled, return ``False``. Otherwise,
161 change the future's state to cancelled, schedule the callbacks and return
162 ``True``.
163
164 .. method:: cancelled()
165
166 Return ``True`` if the future was cancelled.
167
168 .. method:: done()
169
170 Return True if the future is done.
171
172 Done means either that a result / exception are available, or that the
173 future was cancelled.
174
175 .. method:: result()
176
177 Return the result this future represents.
178
179 If the future has been cancelled, raises :exc:`CancelledError`. If the
180 future's result isn't yet available, raises :exc:`InvalidStateError`. If
181 the future is done and has an exception set, this exception is raised.
182
183 .. method:: exception()
184
185 Return the exception that was set on this future.
186
187 The exception (or ``None`` if no exception was set) is returned only if
188 the future is done. If the future has been cancelled, raises
189 :exc:`CancelledError`. If the future isn't done yet, raises
190 :exc:`InvalidStateError`.
191
192 .. method:: add_done_callback(fn)
193
194 Add a callback to be run when the future becomes done.
195
196 The callback is called with a single argument - the future object. If the
197 future is already done when this is called, the callback is scheduled
198 with :meth:`~BaseEventLoop.call_soon`.
199
200 .. method:: remove_done_callback(fn)
201
202 Remove all instances of a callback from the "call when done" list.
203
204 Returns the number of callbacks removed.
205
206 .. method:: set_result(result)
207
208 Mark the future done and set its result.
209
210 If the future is already done when this method is called, raises
211 :exc:`InvalidStateError`.
212
213 .. method:: set_exception(exception)
214
215 Mark the future done and set an exception.
216
217 If the future is already done when this method is called, raises
218 :exc:`InvalidStateError`.
219
220
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100221Example: Future with run_until_complete()
222^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
223
Victor Stinner59759ff2014-01-16 19:30:21 +0100224Example combining a :class:`Future` and a :ref:`coroutine function
225<coroutine>`::
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100226
227 import asyncio
228
229 @asyncio.coroutine
230 def slow_operation(future):
231 yield from asyncio.sleep(1)
232 future.set_result('Future in done!')
233
234 loop = asyncio.get_event_loop()
235 future = asyncio.Future()
236 asyncio.Task(slow_operation(future))
237 loop.run_until_complete(future)
238 print(future.result())
Victor Stinnerf40c6632014-01-28 23:32:40 +0100239 loop.close()
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100240
Victor Stinner59759ff2014-01-16 19:30:21 +0100241The coroutine function is responsible of the computation (which takes 1 second)
242and it stores the result into the future. The
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100243:meth:`~BaseEventLoop.run_until_complete` method waits for the completion of
244the future.
245
246.. note::
247 The :meth:`~BaseEventLoop.run_until_complete` method uses internally the
248 :meth:`~Future.add_done_callback` method to be notified when the future is
249 done.
250
251
252Example: Future with run_forever()
253^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
254
255The previous example can be written differently using the
256:meth:`Future.add_done_callback` method to describe explicitly the control
257flow::
258
259 import asyncio
260
261 @asyncio.coroutine
262 def slow_operation(future):
263 yield from asyncio.sleep(1)
264 future.set_result('Future in done!')
265
266 def got_result(future):
267 print(future.result())
268 loop.stop()
269
270 loop = asyncio.get_event_loop()
271 future = asyncio.Future()
272 asyncio.Task(slow_operation(future))
273 future.add_done_callback(got_result)
274 loop.run_forever()
275
276In this example, the future is responsible to display the result and to stop
277the loop.
278
279.. note::
Victor Stinner59759ff2014-01-16 19:30:21 +0100280 The "slow_operation" coroutine object is only executed when the event loop
281 starts running, so it is possible to add a "done callback" to the future
282 after creating the task scheduling the coroutine object.
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100283
284
285
Victor Stinnerea3183f2013-12-03 01:08:00 +0100286Task
287----
288
289.. class:: Task(coro, \*, loop=None)
290
Victor Stinner59759ff2014-01-16 19:30:21 +0100291 A coroutine object wrapped in a :class:`Future`. Subclass of :class:`Future`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100292
293 .. classmethod:: all_tasks(loop=None)
294
295 Return a set of all tasks for an event loop.
296
297 By default all tasks for the current event loop are returned.
298
Victor Stinner742520b2013-12-10 12:14:50 +0100299 .. classmethod:: current_task(loop=None)
300
301 Return the currently running task in an event loop or ``None``.
302
303 By default the current task for the current event loop is returned.
304
305 ``None`` is returned when called not in the context of a :class:`Task`.
306
Victor Stinnerea3183f2013-12-03 01:08:00 +0100307 .. method:: get_stack(self, \*, limit=None)
308
309 Return the list of stack frames for this task's coroutine.
310
311 If the coroutine is active, this returns the stack where it is suspended.
312 If the coroutine has completed successfully or was cancelled, this
313 returns an empty list. If the coroutine was terminated by an exception,
314 this returns the list of traceback frames.
315
316 The frames are always ordered from oldest to newest.
317
318 The optional limit gives the maximum nummber of frames to return; by
319 default all available frames are returned. Its meaning differs depending
320 on whether a stack or a traceback is returned: the newest frames of a
321 stack are returned, but the oldest frames of a traceback are returned.
322 (This matches the behavior of the traceback module.)
323
324 For reasons beyond our control, only one stack frame is returned for a
325 suspended coroutine.
326
327 .. method:: print_stack(\*, limit=None, file=None)
328
329 Print the stack or traceback for this task's coroutine.
330
331 This produces output similar to that of the traceback module, for the
332 frames retrieved by get_stack(). The limit argument is passed to
333 get_stack(). The file argument is an I/O stream to which the output
334 goes; by default it goes to sys.stderr.
335
336
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100337Example: Parallel execution of tasks
338^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
339
340Example executing 3 tasks (A, B, C) in parallel::
341
342 import asyncio
343
344 @asyncio.coroutine
Victor Stinner34f29462013-12-10 02:51:05 +0100345 def factorial(name, number):
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100346 f = 1
Victor Stinner34f29462013-12-10 02:51:05 +0100347 for i in range(2, number+1):
348 print("Task %s: Compute factorial(%s)..." % (name, i))
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100349 yield from asyncio.sleep(1)
Victor Stinner34f29462013-12-10 02:51:05 +0100350 f *= i
351 print("Task %s: factorial(%s) = %s" % (name, number, f))
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100352
Victor Stinnera6fa1532013-12-10 12:20:14 +0100353 tasks = [
354 asyncio.Task(factorial("A", 2)),
355 asyncio.Task(factorial("B", 3)),
356 asyncio.Task(factorial("C", 4))]
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100357
358 loop = asyncio.get_event_loop()
359 loop.run_until_complete(asyncio.wait(tasks))
Victor Stinnerf40c6632014-01-28 23:32:40 +0100360 loop.close()
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100361
362Output::
363
Victor Stinner34f29462013-12-10 02:51:05 +0100364 Task A: Compute factorial(2)...
365 Task B: Compute factorial(2)...
366 Task C: Compute factorial(2)...
367 Task A: factorial(2) = 2
368 Task B: Compute factorial(3)...
369 Task C: Compute factorial(3)...
370 Task B: factorial(3) = 6
371 Task C: Compute factorial(4)...
372 Task C: factorial(4) = 24
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100373
Victor Stinner34f29462013-12-10 02:51:05 +0100374A task is automatically scheduled for execution when it is created. The event
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100375loop stops when all tasks are done.
376
377
Victor Stinnerea3183f2013-12-03 01:08:00 +0100378Task functions
379--------------
380
Eli Bendersky029981b2014-01-20 07:02:22 -0800381.. note::
382
383 In the functions below, the optional *loop* argument allows to explicitly set
384 the event loop object used by the underlying task or coroutine. If it's
385 not provided, the default event loop is used.
386
Victor Stinner99c2ab42013-12-03 19:17:25 +0100387.. function:: as_completed(fs, \*, loop=None, timeout=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100388
Victor Stinner99c2ab42013-12-03 19:17:25 +0100389 Return an iterator whose values, when waited for, are :class:`Future`
390 instances.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100391
392 Raises :exc:`TimeoutError` if the timeout occurs before all Futures are done.
393
394 Example::
395
396 for f in as_completed(fs):
397 result = yield from f # The 'yield from' may raise
398 # Use result
399
400 .. note::
401
402 The futures ``f`` are not necessarily members of fs.
403
Victor Stinner99c2ab42013-12-03 19:17:25 +0100404.. function:: async(coro_or_future, \*, loop=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100405
Victor Stinner59759ff2014-01-16 19:30:21 +0100406 Wrap a :ref:`coroutine object <coroutine>` in a future.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100407
Victor Stinner99c2ab42013-12-03 19:17:25 +0100408 If the argument is a :class:`Future`, it is returned directly.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100409
Victor Stinner99c2ab42013-12-03 19:17:25 +0100410.. function:: gather(\*coros_or_futures, loop=None, return_exceptions=False)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100411
Victor Stinner59759ff2014-01-16 19:30:21 +0100412 Return a future aggregating results from the given coroutine objects or
413 futures.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100414
415 All futures must share the same event loop. If all the tasks are done
416 successfully, the returned future's result is the list of results (in the
417 order of the original sequence, not necessarily the order of results
418 arrival). If *result_exception* is True, exceptions in the tasks are
419 treated the same as successful results, and gathered in the result list;
420 otherwise, the first raised exception will be immediately propagated to the
421 returned future.
422
423 Cancellation: if the outer Future is cancelled, all children (that have not
424 completed yet) are also cancelled. If any child is cancelled, this is
425 treated as if it raised :exc:`~concurrent.futures.CancelledError` -- the
426 outer Future is *not* cancelled in this case. (This is to prevent the
427 cancellation of one child to cause other children to be cancelled.)
428
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100429.. function:: iscoroutine(obj)
430
431 Return ``True`` if *obj* is a :ref:`coroutine object <coroutine>`.
432
433.. function:: iscoroutinefunction(obj)
434
435 Return ``True`` if *func* is a decorated :ref:`coroutine function
436 <coroutine>`.
437
Victor Stinnerea3183f2013-12-03 01:08:00 +0100438.. function:: sleep(delay, result=None, \*, loop=None)
439
Victor Stinner59759ff2014-01-16 19:30:21 +0100440 Create a :ref:`coroutine object <coroutine>` that completes after a given
Eli Bendersky2d26af82014-01-20 06:59:23 -0800441 time (in seconds). If *result* is provided, it is produced to the caller
442 when the coroutine completes.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100443
Victor Stinner45b27ed2014-02-01 02:36:43 +0100444 The resolution of the sleep depends on the :ref:`granularity of the event
445 loop <asyncio-delayed-calls>`.
446
Victor Stinnerea3183f2013-12-03 01:08:00 +0100447.. function:: shield(arg, \*, loop=None)
448
449 Wait for a future, shielding it from cancellation.
450
451 The statement::
452
453 res = yield from shield(something())
454
455 is exactly equivalent to the statement::
456
457 res = yield from something()
458
459 *except* that if the coroutine containing it is cancelled, the task running
460 in ``something()`` is not cancelled. From the point of view of
461 ``something()``, the cancellation did not happen. But its caller is still
462 cancelled, so the yield-from expression still raises
463 :exc:`~concurrent.futures.CancelledError`. Note: If ``something()`` is
464 cancelled by other means this will still cancel ``shield()``.
465
466 If you want to completely ignore cancellation (not recommended) you can
467 combine ``shield()`` with a try/except clause, as follows::
468
469 try:
470 res = yield from shield(something())
471 except CancelledError:
472 res = None
473
Victor Stinner99c2ab42013-12-03 19:17:25 +0100474.. function:: wait(futures, \*, loop=None, timeout=None, return_when=ALL_COMPLETED)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100475
Victor Stinner59759ff2014-01-16 19:30:21 +0100476 Wait for the Futures and coroutine objects given by the sequence *futures*
477 to complete. Coroutines will be wrapped in Tasks. Returns two sets of
Victor Stinner99c2ab42013-12-03 19:17:25 +0100478 :class:`Future`: (done, pending).
Victor Stinnerea3183f2013-12-03 01:08:00 +0100479
480 *timeout* can be used to control the maximum number of seconds to wait before
481 returning. *timeout* can be an int or float. If *timeout* is not specified
482 or ``None``, there is no limit to the wait time.
483
484 *return_when* indicates when this function should return. It must be one of
Victor Stinner933a8c82013-12-03 01:59:38 +0100485 the following constants of the :mod:`concurrent.futures` module:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100486
487 .. tabularcolumns:: |l|L|
488
489 +-----------------------------+----------------------------------------+
490 | Constant | Description |
491 +=============================+========================================+
492 | :const:`FIRST_COMPLETED` | The function will return when any |
493 | | future finishes or is cancelled. |
494 +-----------------------------+----------------------------------------+
495 | :const:`FIRST_EXCEPTION` | The function will return when any |
496 | | future finishes by raising an |
497 | | exception. If no future raises an |
498 | | exception then it is equivalent to |
499 | | :const:`ALL_COMPLETED`. |
500 +-----------------------------+----------------------------------------+
501 | :const:`ALL_COMPLETED` | The function will return when all |
502 | | futures finish or are cancelled. |
503 +-----------------------------+----------------------------------------+
504
Victor Stinner59759ff2014-01-16 19:30:21 +0100505 This function returns a :ref:`coroutine object <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100506
507 Usage::
508
509 done, pending = yield from asyncio.wait(fs)
510
511 .. note::
512
513 This does not raise :exc:`TimeoutError`! Futures that aren't done when
514 the timeout occurs are returned in the second set.
515
Victor Stinner3e09e322013-12-03 01:22:06 +0100516
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100517.. function:: wait_for(fut, timeout, \*, loop=None)
518
519 Wait for the single :class:`Future` or :ref:`coroutine object <coroutine>`
520 to complete, with timeout. If *timeout* is ``None``, block until the future
521 completes.
522
523 Coroutine will be wrapped in :class:`Task`.
524
525 Returns result of the Future or coroutine. When a timeout occurs, it
526 cancels the task and raises :exc:`TimeoutError`. To avoid the task
527 cancellation, wrap it in :func:`shield`.
528
529 Usage::
530
531 result = yield from asyncio.wait_for(fut, 60.0)
532