blob: 3c031a031a3123d5976ac06323f274f0f62a4a13 [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
59Task
60----
61
62.. class:: Task(coro, \*, loop=None)
63
64 A coroutine wrapped in a :class:`~concurrent.futures.Future`.
65
66 .. classmethod:: all_tasks(loop=None)
67
68 Return a set of all tasks for an event loop.
69
70 By default all tasks for the current event loop are returned.
71
72 .. method:: cancel()
73
74 Cancel the task.
75
76 .. method:: get_stack(self, \*, limit=None)
77
78 Return the list of stack frames for this task's coroutine.
79
80 If the coroutine is active, this returns the stack where it is suspended.
81 If the coroutine has completed successfully or was cancelled, this
82 returns an empty list. If the coroutine was terminated by an exception,
83 this returns the list of traceback frames.
84
85 The frames are always ordered from oldest to newest.
86
87 The optional limit gives the maximum nummber of frames to return; by
88 default all available frames are returned. Its meaning differs depending
89 on whether a stack or a traceback is returned: the newest frames of a
90 stack are returned, but the oldest frames of a traceback are returned.
91 (This matches the behavior of the traceback module.)
92
93 For reasons beyond our control, only one stack frame is returned for a
94 suspended coroutine.
95
96 .. method:: print_stack(\*, limit=None, file=None)
97
98 Print the stack or traceback for this task's coroutine.
99
100 This produces output similar to that of the traceback module, for the
101 frames retrieved by get_stack(). The limit argument is passed to
102 get_stack(). The file argument is an I/O stream to which the output
103 goes; by default it goes to sys.stderr.
104
105
106Task functions
107--------------
108
109.. function:: as_completed(fs, *, loop=None, timeout=None)
110
111 Return an iterator whose values, when waited for, are
112 :class:`~concurrent.futures.Future` instances.
113
114 Raises :exc:`TimeoutError` if the timeout occurs before all Futures are done.
115
116 Example::
117
118 for f in as_completed(fs):
119 result = yield from f # The 'yield from' may raise
120 # Use result
121
122 .. note::
123
124 The futures ``f`` are not necessarily members of fs.
125
126.. function:: async(coro_or_future, *, loop=None)
127
128 Wrap a :ref:`coroutine <coroutine>` in a future.
129
130 If the argument is a :class:`~concurrent.futures.Future`, it is returned
131 directly.
132
133.. function:: gather(*coros_or_futures, loop=None, return_exceptions=False)
134
135 Return a future aggregating results from the given coroutines or futures.
136
137 All futures must share the same event loop. If all the tasks are done
138 successfully, the returned future's result is the list of results (in the
139 order of the original sequence, not necessarily the order of results
140 arrival). If *result_exception* is True, exceptions in the tasks are
141 treated the same as successful results, and gathered in the result list;
142 otherwise, the first raised exception will be immediately propagated to the
143 returned future.
144
145 Cancellation: if the outer Future is cancelled, all children (that have not
146 completed yet) are also cancelled. If any child is cancelled, this is
147 treated as if it raised :exc:`~concurrent.futures.CancelledError` -- the
148 outer Future is *not* cancelled in this case. (This is to prevent the
149 cancellation of one child to cause other children to be cancelled.)
150
151.. function:: tasks.iscoroutinefunction(func)
152
153 Return ``True`` if *func* is a decorated coroutine function.
154
155.. function:: tasks.iscoroutine(obj)
156
157 Return ``True`` if *obj* is a coroutine object.
158
159.. function:: sleep(delay, result=None, \*, loop=None)
160
161 Create a :ref:`coroutine <coroutine>` that completes after a given time
162 (in seconds).
163
164.. function:: shield(arg, \*, loop=None)
165
166 Wait for a future, shielding it from cancellation.
167
168 The statement::
169
170 res = yield from shield(something())
171
172 is exactly equivalent to the statement::
173
174 res = yield from something()
175
176 *except* that if the coroutine containing it is cancelled, the task running
177 in ``something()`` is not cancelled. From the point of view of
178 ``something()``, the cancellation did not happen. But its caller is still
179 cancelled, so the yield-from expression still raises
180 :exc:`~concurrent.futures.CancelledError`. Note: If ``something()`` is
181 cancelled by other means this will still cancel ``shield()``.
182
183 If you want to completely ignore cancellation (not recommended) you can
184 combine ``shield()`` with a try/except clause, as follows::
185
186 try:
187 res = yield from shield(something())
188 except CancelledError:
189 res = None
190
191.. function:: wait(fs, \*, loop=None, timeout=None, return_when=ALL_COMPLETED)
192
193 Wait for the Futures and coroutines given by fs to complete. Coroutines will
194 be wrapped in Tasks. Returns two sets of
195 :class:`~concurrent.futures.Future`: (done, pending).
196
197 *timeout* can be used to control the maximum number of seconds to wait before
198 returning. *timeout* can be an int or float. If *timeout* is not specified
199 or ``None``, there is no limit to the wait time.
200
201 *return_when* indicates when this function should return. It must be one of
Victor Stinner933a8c82013-12-03 01:59:38 +0100202 the following constants of the :mod:`concurrent.futures` module:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100203
204 .. tabularcolumns:: |l|L|
205
206 +-----------------------------+----------------------------------------+
207 | Constant | Description |
208 +=============================+========================================+
209 | :const:`FIRST_COMPLETED` | The function will return when any |
210 | | future finishes or is cancelled. |
211 +-----------------------------+----------------------------------------+
212 | :const:`FIRST_EXCEPTION` | The function will return when any |
213 | | future finishes by raising an |
214 | | exception. If no future raises an |
215 | | exception then it is equivalent to |
216 | | :const:`ALL_COMPLETED`. |
217 +-----------------------------+----------------------------------------+
218 | :const:`ALL_COMPLETED` | The function will return when all |
219 | | futures finish or are cancelled. |
220 +-----------------------------+----------------------------------------+
221
222 This function returns a :ref:`coroutine <coroutine>`.
223
224 Usage::
225
226 done, pending = yield from asyncio.wait(fs)
227
228 .. note::
229
230 This does not raise :exc:`TimeoutError`! Futures that aren't done when
231 the timeout occurs are returned in the second set.
232
Victor Stinner3e09e322013-12-03 01:22:06 +0100233
Victor Stinnerc6fba922013-12-03 17:37:31 +0100234Examples
235--------
236
237
Victor Stinner3e09e322013-12-03 01:22:06 +0100238.. _asyncio-hello-world-coroutine:
239
240Example: Hello World (coroutine)
Victor Stinnerc6fba922013-12-03 17:37:31 +0100241^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinner3e09e322013-12-03 01:22:06 +0100242
243Print ``Hello World`` every two seconds, using a coroutine::
244
245 import asyncio
246
247 @asyncio.coroutine
248 def greet_every_two_seconds():
249 while True:
250 print('Hello World')
251 yield from asyncio.sleep(2)
252
253 loop = asyncio.get_event_loop()
254 loop.run_until_complete(greet_every_two_seconds())
255
256
257.. seealso::
258
259 :ref:`Hello World example using a callback <asyncio-hello-world-callback>`.
Victor Stinnerc6fba922013-12-03 17:37:31 +0100260
261Example: Chains coroutines and parallel execution
262^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
263
264Example chaining coroutines and executing multiple coroutines in parallel::
265
266 import asyncio
267
268 @asyncio.coroutine
269 def compute(x, y):
270 print("Start computing %s + %s" % (x, y))
271 yield from asyncio.sleep(3.0)
272 return x + y
273
274 @asyncio.coroutine
275 def print_sum(x, y):
276 result = yield from compute(x, y)
277 print("%s + %s = %s" % (x, y, result))
278
279 @asyncio.coroutine
280 def wait_task(task):
281 while 1:
282 done, pending = yield from asyncio.wait([task], timeout=1.0)
283 if done:
284 break
285 print("Compute in progress...")
286 asyncio.get_event_loop().stop()
287
288 print("Schedule tasks")
289 task = asyncio.async(print_sum(1, 2))
290 asyncio.async(wait_task(task))
291
292 print("Execute tasks")
293 loop = asyncio.get_event_loop()
294 loop.run_forever()
295 loop.close()
296
297
298
299Output::
300
301 Schedule tasks
302 Execute tasks
303 Start computing 1 + 2
304 Compute in progress...
305 Compute in progress...
306 1 + 2 = 3
307
308Details:
309
310* ``compute()`` is chained to ``print_sum()``: ``print_sum()`` coroutine waits
311 until ``compute()`` is complete. Coroutines are executed in parallel:
312 ``wait_task()`` is executed while ``compute()`` is blocked in
313 ``asyncio.sleep(3.0)``.
314
315* Coroutines are not executed before the loop is running: ``"Execute tasks"``
316 is written before ``"Start computing 1 + 2"``.
317
318* ``wait_task()`` stops the event loop when ``print_sum()`` is done.
319