blob: 43b506008cee15582e1571d6ba9d33b36a598c9f [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 Stinnerea3183f2013-12-03 01:08:00 +010023 we will call this a *coroutine function*.
24
25- The object obtained by calling a coroutine function. This object
26 represents a computation or an I/O operation (usually a combination)
27 that will complete eventually. If disambiguation is needed we will
28 call it a *coroutine object*.
29
30Things a coroutine can do:
31
32- ``result = yield from future`` -- suspends the coroutine until the
33 future is done, then returns the future's result, or raises an
34 exception, which will be propagated. (If the future is cancelled,
35 it will raise a ``CancelledError`` exception.) Note that tasks are
36 futures, and everything said about futures also applies to tasks.
37
38- ``result = yield from coroutine`` -- wait for another coroutine to
39 produce a result (or raise an exception, which will be propagated).
40 The ``coroutine`` expression must be a *call* to another coroutine.
41
42- ``return expression`` -- produce a result to the coroutine that is
43 waiting for this one using ``yield from``.
44
45- ``raise exception`` -- raise an exception in the coroutine that is
46 waiting for this one using ``yield from``.
47
48Calling a coroutine does not start its code running -- it is just a
49generator, and the coroutine object returned by the call is really a
50generator object, which doesn't do anything until you iterate over it.
51In the case of a coroutine object, there are two basic ways to start
52it running: call ``yield from coroutine`` from another coroutine
53(assuming the other coroutine is already running!), or convert it to a
54:class:`Task`.
55
56Coroutines (and tasks) can only run when the event loop is running.
57
Victor Stinnerdb39a0d2014-01-16 18:58:01 +010058.. decorator:: coroutine
59
60 Decorator to mark coroutines.
61
62 If the coroutine is not yielded from before it is destroyed, an error
63 message is logged. See :ref:`Detect coroutines never scheduled
64 <asyncio-coroutine-not-scheduled>`.
65
Victor Stinnerea3183f2013-12-03 01:08:00 +010066
Victor Stinnerb69d62d2013-12-10 02:09:46 +010067.. _asyncio-hello-world-coroutine:
68
69Example: "Hello World" coroutine
70^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
71
72Print ``"Hello World"`` every two seconds using a coroutine::
73
74 import asyncio
75
76 @asyncio.coroutine
77 def greet_every_two_seconds():
78 while True:
79 print('Hello World')
80 yield from asyncio.sleep(2)
81
82 loop = asyncio.get_event_loop()
83 loop.run_until_complete(greet_every_two_seconds())
84
Victor Stinnerb69d62d2013-12-10 02:09:46 +010085.. seealso::
86
87 :ref:`Hello World example using a callback <asyncio-hello-world-callback>`.
88
89
90Example: Chain coroutines
91^^^^^^^^^^^^^^^^^^^^^^^^^
92
93Example chaining coroutines::
94
95 import asyncio
96
97 @asyncio.coroutine
98 def compute(x, y):
99 print("Compute %s + %s ..." % (x, y))
100 yield from asyncio.sleep(1.0)
101 return x + y
102
103 @asyncio.coroutine
104 def print_sum(x, y):
105 result = yield from compute(x, y)
106 print("%s + %s = %s" % (x, y, result))
107
108 loop = asyncio.get_event_loop()
109 loop.run_until_complete(print_sum(1, 2))
110
111``compute()`` is chained to ``print_sum()``: ``print_sum()`` coroutine waits
112until ``compute()`` is completed before returing its result.
113
Victor Stinner1c4b8922013-12-12 12:35:17 +0100114Sequence diagram of the example:
115
116.. image:: tulip_coro.png
117 :align: center
118
Victor Stinner86e139a2013-12-13 12:51:24 +0100119The "Task" is created by the :meth:`BaseEventLoop.run_until_complete` method
Victor Stinner59759ff2014-01-16 19:30:21 +0100120when it gets a coroutine object instead of a task.
Victor Stinner86e139a2013-12-13 12:51:24 +0100121
122The diagram shows the control flow, it does not describe exactly how things
123work internally. For example, the sleep coroutine creates an internal future
124which uses :meth:`BaseEventLoop.call_later` to wake up the task in 1 second.
Victor Stinner1c4b8922013-12-12 12:35:17 +0100125
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100126
Victor Stinner99c2ab42013-12-03 19:17:25 +0100127InvalidStateError
128-----------------
129
130.. exception:: InvalidStateError
131
132 The operation is not allowed in this state.
133
134
135Future
136------
137
138.. class:: Future(\*, loop=None)
139
140 This class is *almost* compatible with :class:`concurrent.futures.Future`.
141
142 Differences:
143
144 - :meth:`result` and :meth:`exception` do not take a timeout argument and
145 raise an exception when the future isn't done yet.
146
147 - Callbacks registered with :meth:`add_done_callback` are always called
148 via the event loop's :meth:`~BaseEventLoop.call_soon_threadsafe`.
149
150 - This class is not compatible with the :func:`~concurrent.futures.wait` and
151 :func:`~concurrent.futures.as_completed` functions in the
152 :mod:`concurrent.futures` package.
153
154 .. method:: cancel()
155
156 Cancel the future and schedule callbacks.
157
158 If the future is already done or cancelled, return ``False``. Otherwise,
159 change the future's state to cancelled, schedule the callbacks and return
160 ``True``.
161
162 .. method:: cancelled()
163
164 Return ``True`` if the future was cancelled.
165
166 .. method:: done()
167
168 Return True if the future is done.
169
170 Done means either that a result / exception are available, or that the
171 future was cancelled.
172
173 .. method:: result()
174
175 Return the result this future represents.
176
177 If the future has been cancelled, raises :exc:`CancelledError`. If the
178 future's result isn't yet available, raises :exc:`InvalidStateError`. If
179 the future is done and has an exception set, this exception is raised.
180
181 .. method:: exception()
182
183 Return the exception that was set on this future.
184
185 The exception (or ``None`` if no exception was set) is returned only if
186 the future is done. If the future has been cancelled, raises
187 :exc:`CancelledError`. If the future isn't done yet, raises
188 :exc:`InvalidStateError`.
189
190 .. method:: add_done_callback(fn)
191
192 Add a callback to be run when the future becomes done.
193
194 The callback is called with a single argument - the future object. If the
195 future is already done when this is called, the callback is scheduled
196 with :meth:`~BaseEventLoop.call_soon`.
197
198 .. method:: remove_done_callback(fn)
199
200 Remove all instances of a callback from the "call when done" list.
201
202 Returns the number of callbacks removed.
203
204 .. method:: set_result(result)
205
206 Mark the future done and set its result.
207
208 If the future is already done when this method is called, raises
209 :exc:`InvalidStateError`.
210
211 .. method:: set_exception(exception)
212
213 Mark the future done and set an exception.
214
215 If the future is already done when this method is called, raises
216 :exc:`InvalidStateError`.
217
218
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100219Example: Future with run_until_complete()
220^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
221
Victor Stinner59759ff2014-01-16 19:30:21 +0100222Example combining a :class:`Future` and a :ref:`coroutine function
223<coroutine>`::
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100224
225 import asyncio
226
227 @asyncio.coroutine
228 def slow_operation(future):
229 yield from asyncio.sleep(1)
230 future.set_result('Future in done!')
231
232 loop = asyncio.get_event_loop()
233 future = asyncio.Future()
234 asyncio.Task(slow_operation(future))
235 loop.run_until_complete(future)
236 print(future.result())
237
Victor Stinner59759ff2014-01-16 19:30:21 +0100238The coroutine function is responsible of the computation (which takes 1 second)
239and it stores the result into the future. The
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100240:meth:`~BaseEventLoop.run_until_complete` method waits for the completion of
241the future.
242
243.. note::
244 The :meth:`~BaseEventLoop.run_until_complete` method uses internally the
245 :meth:`~Future.add_done_callback` method to be notified when the future is
246 done.
247
248
249Example: Future with run_forever()
250^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
251
252The previous example can be written differently using the
253:meth:`Future.add_done_callback` method to describe explicitly the control
254flow::
255
256 import asyncio
257
258 @asyncio.coroutine
259 def slow_operation(future):
260 yield from asyncio.sleep(1)
261 future.set_result('Future in done!')
262
263 def got_result(future):
264 print(future.result())
265 loop.stop()
266
267 loop = asyncio.get_event_loop()
268 future = asyncio.Future()
269 asyncio.Task(slow_operation(future))
270 future.add_done_callback(got_result)
271 loop.run_forever()
272
273In this example, the future is responsible to display the result and to stop
274the loop.
275
276.. note::
Victor Stinner59759ff2014-01-16 19:30:21 +0100277 The "slow_operation" coroutine object is only executed when the event loop
278 starts running, so it is possible to add a "done callback" to the future
279 after creating the task scheduling the coroutine object.
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100280
281
282
Victor Stinnerea3183f2013-12-03 01:08:00 +0100283Task
284----
285
286.. class:: Task(coro, \*, loop=None)
287
Victor Stinner59759ff2014-01-16 19:30:21 +0100288 A coroutine object wrapped in a :class:`Future`. Subclass of :class:`Future`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100289
290 .. classmethod:: all_tasks(loop=None)
291
292 Return a set of all tasks for an event loop.
293
294 By default all tasks for the current event loop are returned.
295
Victor Stinner742520b2013-12-10 12:14:50 +0100296 .. classmethod:: current_task(loop=None)
297
298 Return the currently running task in an event loop or ``None``.
299
300 By default the current task for the current event loop is returned.
301
302 ``None`` is returned when called not in the context of a :class:`Task`.
303
Victor Stinnerea3183f2013-12-03 01:08:00 +0100304 .. method:: get_stack(self, \*, limit=None)
305
306 Return the list of stack frames for this task's coroutine.
307
308 If the coroutine is active, this returns the stack where it is suspended.
309 If the coroutine has completed successfully or was cancelled, this
310 returns an empty list. If the coroutine was terminated by an exception,
311 this returns the list of traceback frames.
312
313 The frames are always ordered from oldest to newest.
314
315 The optional limit gives the maximum nummber of frames to return; by
316 default all available frames are returned. Its meaning differs depending
317 on whether a stack or a traceback is returned: the newest frames of a
318 stack are returned, but the oldest frames of a traceback are returned.
319 (This matches the behavior of the traceback module.)
320
321 For reasons beyond our control, only one stack frame is returned for a
322 suspended coroutine.
323
324 .. method:: print_stack(\*, limit=None, file=None)
325
326 Print the stack or traceback for this task's coroutine.
327
328 This produces output similar to that of the traceback module, for the
329 frames retrieved by get_stack(). The limit argument is passed to
330 get_stack(). The file argument is an I/O stream to which the output
331 goes; by default it goes to sys.stderr.
332
333
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100334Example: Parallel execution of tasks
335^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
336
337Example executing 3 tasks (A, B, C) in parallel::
338
339 import asyncio
340
341 @asyncio.coroutine
Victor Stinner34f29462013-12-10 02:51:05 +0100342 def factorial(name, number):
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100343 f = 1
Victor Stinner34f29462013-12-10 02:51:05 +0100344 for i in range(2, number+1):
345 print("Task %s: Compute factorial(%s)..." % (name, i))
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100346 yield from asyncio.sleep(1)
Victor Stinner34f29462013-12-10 02:51:05 +0100347 f *= i
348 print("Task %s: factorial(%s) = %s" % (name, number, f))
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100349
Victor Stinnera6fa1532013-12-10 12:20:14 +0100350 tasks = [
351 asyncio.Task(factorial("A", 2)),
352 asyncio.Task(factorial("B", 3)),
353 asyncio.Task(factorial("C", 4))]
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100354
355 loop = asyncio.get_event_loop()
356 loop.run_until_complete(asyncio.wait(tasks))
357
358Output::
359
Victor Stinner34f29462013-12-10 02:51:05 +0100360 Task A: Compute factorial(2)...
361 Task B: Compute factorial(2)...
362 Task C: Compute factorial(2)...
363 Task A: factorial(2) = 2
364 Task B: Compute factorial(3)...
365 Task C: Compute factorial(3)...
366 Task B: factorial(3) = 6
367 Task C: Compute factorial(4)...
368 Task C: factorial(4) = 24
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100369
Victor Stinner34f29462013-12-10 02:51:05 +0100370A task is automatically scheduled for execution when it is created. The event
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100371loop stops when all tasks are done.
372
373
Victor Stinnerea3183f2013-12-03 01:08:00 +0100374Task functions
375--------------
376
Victor Stinner99c2ab42013-12-03 19:17:25 +0100377.. function:: as_completed(fs, \*, loop=None, timeout=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100378
Victor Stinner99c2ab42013-12-03 19:17:25 +0100379 Return an iterator whose values, when waited for, are :class:`Future`
380 instances.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100381
382 Raises :exc:`TimeoutError` if the timeout occurs before all Futures are done.
383
384 Example::
385
386 for f in as_completed(fs):
387 result = yield from f # The 'yield from' may raise
388 # Use result
389
390 .. note::
391
392 The futures ``f`` are not necessarily members of fs.
393
Victor Stinner99c2ab42013-12-03 19:17:25 +0100394.. function:: async(coro_or_future, \*, loop=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100395
Victor Stinner59759ff2014-01-16 19:30:21 +0100396 Wrap a :ref:`coroutine object <coroutine>` in a future.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100397
Victor Stinner99c2ab42013-12-03 19:17:25 +0100398 If the argument is a :class:`Future`, it is returned directly.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100399
Victor Stinner99c2ab42013-12-03 19:17:25 +0100400.. function:: gather(\*coros_or_futures, loop=None, return_exceptions=False)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100401
Victor Stinner59759ff2014-01-16 19:30:21 +0100402 Return a future aggregating results from the given coroutine objects or
403 futures.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100404
405 All futures must share the same event loop. If all the tasks are done
406 successfully, the returned future's result is the list of results (in the
407 order of the original sequence, not necessarily the order of results
408 arrival). If *result_exception* is True, exceptions in the tasks are
409 treated the same as successful results, and gathered in the result list;
410 otherwise, the first raised exception will be immediately propagated to the
411 returned future.
412
413 Cancellation: if the outer Future is cancelled, all children (that have not
414 completed yet) are also cancelled. If any child is cancelled, this is
415 treated as if it raised :exc:`~concurrent.futures.CancelledError` -- the
416 outer Future is *not* cancelled in this case. (This is to prevent the
417 cancellation of one child to cause other children to be cancelled.)
418
Victor Stinnerea3183f2013-12-03 01:08:00 +0100419.. function:: sleep(delay, result=None, \*, loop=None)
420
Victor Stinner59759ff2014-01-16 19:30:21 +0100421 Create a :ref:`coroutine object <coroutine>` that completes after a given
422 time (in seconds).
Victor Stinnerea3183f2013-12-03 01:08:00 +0100423
424.. function:: shield(arg, \*, loop=None)
425
426 Wait for a future, shielding it from cancellation.
427
428 The statement::
429
430 res = yield from shield(something())
431
432 is exactly equivalent to the statement::
433
434 res = yield from something()
435
436 *except* that if the coroutine containing it is cancelled, the task running
437 in ``something()`` is not cancelled. From the point of view of
438 ``something()``, the cancellation did not happen. But its caller is still
439 cancelled, so the yield-from expression still raises
440 :exc:`~concurrent.futures.CancelledError`. Note: If ``something()`` is
441 cancelled by other means this will still cancel ``shield()``.
442
443 If you want to completely ignore cancellation (not recommended) you can
444 combine ``shield()`` with a try/except clause, as follows::
445
446 try:
447 res = yield from shield(something())
448 except CancelledError:
449 res = None
450
Victor Stinner99c2ab42013-12-03 19:17:25 +0100451.. function:: wait(futures, \*, loop=None, timeout=None, return_when=ALL_COMPLETED)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100452
Victor Stinner59759ff2014-01-16 19:30:21 +0100453 Wait for the Futures and coroutine objects given by the sequence *futures*
454 to complete. Coroutines will be wrapped in Tasks. Returns two sets of
Victor Stinner99c2ab42013-12-03 19:17:25 +0100455 :class:`Future`: (done, pending).
Victor Stinnerea3183f2013-12-03 01:08:00 +0100456
457 *timeout* can be used to control the maximum number of seconds to wait before
458 returning. *timeout* can be an int or float. If *timeout* is not specified
459 or ``None``, there is no limit to the wait time.
460
461 *return_when* indicates when this function should return. It must be one of
Victor Stinner933a8c82013-12-03 01:59:38 +0100462 the following constants of the :mod:`concurrent.futures` module:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100463
464 .. tabularcolumns:: |l|L|
465
466 +-----------------------------+----------------------------------------+
467 | Constant | Description |
468 +=============================+========================================+
469 | :const:`FIRST_COMPLETED` | The function will return when any |
470 | | future finishes or is cancelled. |
471 +-----------------------------+----------------------------------------+
472 | :const:`FIRST_EXCEPTION` | The function will return when any |
473 | | future finishes by raising an |
474 | | exception. If no future raises an |
475 | | exception then it is equivalent to |
476 | | :const:`ALL_COMPLETED`. |
477 +-----------------------------+----------------------------------------+
478 | :const:`ALL_COMPLETED` | The function will return when all |
479 | | futures finish or are cancelled. |
480 +-----------------------------+----------------------------------------+
481
Victor Stinner59759ff2014-01-16 19:30:21 +0100482 This function returns a :ref:`coroutine object <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100483
484 Usage::
485
486 done, pending = yield from asyncio.wait(fs)
487
488 .. note::
489
490 This does not raise :exc:`TimeoutError`! Futures that aren't done when
491 the timeout occurs are returned in the second set.
492
Victor Stinner3e09e322013-12-03 01:22:06 +0100493