blob: 920562fc1a7c3e2485e5758b94989534abda770f [file] [log] [blame]
Victor Stinnerea3183f2013-12-03 01:08:00 +01001.. module:: asyncio
2
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
22 decorated with ``asyncio.coroutine``). If disambiguation is needed
23 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
58
Victor Stinner99c2ab42013-12-03 19:17:25 +010059InvalidStateError
60-----------------
61
62.. exception:: InvalidStateError
63
64 The operation is not allowed in this state.
65
66
67Future
68------
69
70.. class:: Future(\*, loop=None)
71
72 This class is *almost* compatible with :class:`concurrent.futures.Future`.
73
74 Differences:
75
76 - :meth:`result` and :meth:`exception` do not take a timeout argument and
77 raise an exception when the future isn't done yet.
78
79 - Callbacks registered with :meth:`add_done_callback` are always called
80 via the event loop's :meth:`~BaseEventLoop.call_soon_threadsafe`.
81
82 - This class is not compatible with the :func:`~concurrent.futures.wait` and
83 :func:`~concurrent.futures.as_completed` functions in the
84 :mod:`concurrent.futures` package.
85
86 .. method:: cancel()
87
88 Cancel the future and schedule callbacks.
89
90 If the future is already done or cancelled, return ``False``. Otherwise,
91 change the future's state to cancelled, schedule the callbacks and return
92 ``True``.
93
94 .. method:: cancelled()
95
96 Return ``True`` if the future was cancelled.
97
98 .. method:: done()
99
100 Return True if the future is done.
101
102 Done means either that a result / exception are available, or that the
103 future was cancelled.
104
105 .. method:: result()
106
107 Return the result this future represents.
108
109 If the future has been cancelled, raises :exc:`CancelledError`. If the
110 future's result isn't yet available, raises :exc:`InvalidStateError`. If
111 the future is done and has an exception set, this exception is raised.
112
113 .. method:: exception()
114
115 Return the exception that was set on this future.
116
117 The exception (or ``None`` if no exception was set) is returned only if
118 the future is done. If the future has been cancelled, raises
119 :exc:`CancelledError`. If the future isn't done yet, raises
120 :exc:`InvalidStateError`.
121
122 .. method:: add_done_callback(fn)
123
124 Add a callback to be run when the future becomes done.
125
126 The callback is called with a single argument - the future object. If the
127 future is already done when this is called, the callback is scheduled
128 with :meth:`~BaseEventLoop.call_soon`.
129
130 .. method:: remove_done_callback(fn)
131
132 Remove all instances of a callback from the "call when done" list.
133
134 Returns the number of callbacks removed.
135
136 .. method:: set_result(result)
137
138 Mark the future done and set its result.
139
140 If the future is already done when this method is called, raises
141 :exc:`InvalidStateError`.
142
143 .. method:: set_exception(exception)
144
145 Mark the future done and set an exception.
146
147 If the future is already done when this method is called, raises
148 :exc:`InvalidStateError`.
149
150
Victor Stinnerea3183f2013-12-03 01:08:00 +0100151Task
152----
153
154.. class:: Task(coro, \*, loop=None)
155
Victor Stinner99c2ab42013-12-03 19:17:25 +0100156 A coroutine wrapped in a :class:`Future`. Subclass of :class:`Future`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100157
158 .. classmethod:: all_tasks(loop=None)
159
160 Return a set of all tasks for an event loop.
161
162 By default all tasks for the current event loop are returned.
163
164 .. method:: cancel()
165
166 Cancel the task.
167
168 .. method:: get_stack(self, \*, limit=None)
169
170 Return the list of stack frames for this task's coroutine.
171
172 If the coroutine is active, this returns the stack where it is suspended.
173 If the coroutine has completed successfully or was cancelled, this
174 returns an empty list. If the coroutine was terminated by an exception,
175 this returns the list of traceback frames.
176
177 The frames are always ordered from oldest to newest.
178
179 The optional limit gives the maximum nummber of frames to return; by
180 default all available frames are returned. Its meaning differs depending
181 on whether a stack or a traceback is returned: the newest frames of a
182 stack are returned, but the oldest frames of a traceback are returned.
183 (This matches the behavior of the traceback module.)
184
185 For reasons beyond our control, only one stack frame is returned for a
186 suspended coroutine.
187
188 .. method:: print_stack(\*, limit=None, file=None)
189
190 Print the stack or traceback for this task's coroutine.
191
192 This produces output similar to that of the traceback module, for the
193 frames retrieved by get_stack(). The limit argument is passed to
194 get_stack(). The file argument is an I/O stream to which the output
195 goes; by default it goes to sys.stderr.
196
197
198Task functions
199--------------
200
Victor Stinner99c2ab42013-12-03 19:17:25 +0100201.. function:: as_completed(fs, \*, loop=None, timeout=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100202
Victor Stinner99c2ab42013-12-03 19:17:25 +0100203 Return an iterator whose values, when waited for, are :class:`Future`
204 instances.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100205
206 Raises :exc:`TimeoutError` if the timeout occurs before all Futures are done.
207
208 Example::
209
210 for f in as_completed(fs):
211 result = yield from f # The 'yield from' may raise
212 # Use result
213
214 .. note::
215
216 The futures ``f`` are not necessarily members of fs.
217
Victor Stinner99c2ab42013-12-03 19:17:25 +0100218.. function:: async(coro_or_future, \*, loop=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100219
220 Wrap a :ref:`coroutine <coroutine>` in a future.
221
Victor Stinner99c2ab42013-12-03 19:17:25 +0100222 If the argument is a :class:`Future`, it is returned directly.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100223
Victor Stinner99c2ab42013-12-03 19:17:25 +0100224.. function:: gather(\*coros_or_futures, loop=None, return_exceptions=False)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100225
226 Return a future aggregating results from the given coroutines or futures.
227
228 All futures must share the same event loop. If all the tasks are done
229 successfully, the returned future's result is the list of results (in the
230 order of the original sequence, not necessarily the order of results
231 arrival). If *result_exception* is True, exceptions in the tasks are
232 treated the same as successful results, and gathered in the result list;
233 otherwise, the first raised exception will be immediately propagated to the
234 returned future.
235
236 Cancellation: if the outer Future is cancelled, all children (that have not
237 completed yet) are also cancelled. If any child is cancelled, this is
238 treated as if it raised :exc:`~concurrent.futures.CancelledError` -- the
239 outer Future is *not* cancelled in this case. (This is to prevent the
240 cancellation of one child to cause other children to be cancelled.)
241
242.. function:: tasks.iscoroutinefunction(func)
243
244 Return ``True`` if *func* is a decorated coroutine function.
245
246.. function:: tasks.iscoroutine(obj)
247
248 Return ``True`` if *obj* is a coroutine object.
249
250.. function:: sleep(delay, result=None, \*, loop=None)
251
252 Create a :ref:`coroutine <coroutine>` that completes after a given time
253 (in seconds).
254
255.. function:: shield(arg, \*, loop=None)
256
257 Wait for a future, shielding it from cancellation.
258
259 The statement::
260
261 res = yield from shield(something())
262
263 is exactly equivalent to the statement::
264
265 res = yield from something()
266
267 *except* that if the coroutine containing it is cancelled, the task running
268 in ``something()`` is not cancelled. From the point of view of
269 ``something()``, the cancellation did not happen. But its caller is still
270 cancelled, so the yield-from expression still raises
271 :exc:`~concurrent.futures.CancelledError`. Note: If ``something()`` is
272 cancelled by other means this will still cancel ``shield()``.
273
274 If you want to completely ignore cancellation (not recommended) you can
275 combine ``shield()`` with a try/except clause, as follows::
276
277 try:
278 res = yield from shield(something())
279 except CancelledError:
280 res = None
281
Victor Stinner99c2ab42013-12-03 19:17:25 +0100282.. function:: wait(futures, \*, loop=None, timeout=None, return_when=ALL_COMPLETED)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100283
Victor Stinner99c2ab42013-12-03 19:17:25 +0100284 Wait for the Futures and coroutines given by the sequence *futures* to
285 complete. Coroutines will be wrapped in Tasks. Returns two sets of
286 :class:`Future`: (done, pending).
Victor Stinnerea3183f2013-12-03 01:08:00 +0100287
288 *timeout* can be used to control the maximum number of seconds to wait before
289 returning. *timeout* can be an int or float. If *timeout* is not specified
290 or ``None``, there is no limit to the wait time.
291
292 *return_when* indicates when this function should return. It must be one of
Victor Stinner933a8c82013-12-03 01:59:38 +0100293 the following constants of the :mod:`concurrent.futures` module:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100294
295 .. tabularcolumns:: |l|L|
296
297 +-----------------------------+----------------------------------------+
298 | Constant | Description |
299 +=============================+========================================+
300 | :const:`FIRST_COMPLETED` | The function will return when any |
301 | | future finishes or is cancelled. |
302 +-----------------------------+----------------------------------------+
303 | :const:`FIRST_EXCEPTION` | The function will return when any |
304 | | future finishes by raising an |
305 | | exception. If no future raises an |
306 | | exception then it is equivalent to |
307 | | :const:`ALL_COMPLETED`. |
308 +-----------------------------+----------------------------------------+
309 | :const:`ALL_COMPLETED` | The function will return when all |
310 | | futures finish or are cancelled. |
311 +-----------------------------+----------------------------------------+
312
313 This function returns a :ref:`coroutine <coroutine>`.
314
315 Usage::
316
317 done, pending = yield from asyncio.wait(fs)
318
319 .. note::
320
321 This does not raise :exc:`TimeoutError`! Futures that aren't done when
322 the timeout occurs are returned in the second set.
323
Victor Stinner3e09e322013-12-03 01:22:06 +0100324
Victor Stinnerc6fba922013-12-03 17:37:31 +0100325Examples
326--------
327
328
Victor Stinner3e09e322013-12-03 01:22:06 +0100329.. _asyncio-hello-world-coroutine:
330
331Example: Hello World (coroutine)
Victor Stinnerc6fba922013-12-03 17:37:31 +0100332^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinner3e09e322013-12-03 01:22:06 +0100333
334Print ``Hello World`` every two seconds, using a coroutine::
335
336 import asyncio
337
338 @asyncio.coroutine
339 def greet_every_two_seconds():
340 while True:
341 print('Hello World')
342 yield from asyncio.sleep(2)
343
344 loop = asyncio.get_event_loop()
345 loop.run_until_complete(greet_every_two_seconds())
346
347
348.. seealso::
349
350 :ref:`Hello World example using a callback <asyncio-hello-world-callback>`.
Victor Stinnerc6fba922013-12-03 17:37:31 +0100351
352Example: Chains coroutines and parallel execution
353^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
354
355Example chaining coroutines and executing multiple coroutines in parallel::
356
357 import asyncio
358
359 @asyncio.coroutine
360 def compute(x, y):
361 print("Start computing %s + %s" % (x, y))
362 yield from asyncio.sleep(3.0)
363 return x + y
364
365 @asyncio.coroutine
366 def print_sum(x, y):
367 result = yield from compute(x, y)
368 print("%s + %s = %s" % (x, y, result))
369
370 @asyncio.coroutine
371 def wait_task(task):
372 while 1:
373 done, pending = yield from asyncio.wait([task], timeout=1.0)
374 if done:
375 break
376 print("Compute in progress...")
377 asyncio.get_event_loop().stop()
378
379 print("Schedule tasks")
380 task = asyncio.async(print_sum(1, 2))
381 asyncio.async(wait_task(task))
382
383 print("Execute tasks")
384 loop = asyncio.get_event_loop()
385 loop.run_forever()
386 loop.close()
387
388
389
390Output::
391
392 Schedule tasks
393 Execute tasks
394 Start computing 1 + 2
395 Compute in progress...
396 Compute in progress...
397 1 + 2 = 3
398
399Details:
400
401* ``compute()`` is chained to ``print_sum()``: ``print_sum()`` coroutine waits
402 until ``compute()`` is complete. Coroutines are executed in parallel:
403 ``wait_task()`` is executed while ``compute()`` is blocked in
404 ``asyncio.sleep(3.0)``.
405
406* Coroutines are not executed before the loop is running: ``"Execute tasks"``
407 is written before ``"Start computing 1 + 2"``.
408
409* ``wait_task()`` stops the event loop when ``print_sum()`` is done.
410