blob: 804f1925b409298ac493f5a49e4b6ab8e0738dd2 [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
Yury Selivanov66f88282015-06-24 11:04:15 -040011Coroutines used with :mod:`asyncio` may be implemented using the
12:keyword:`async def` statement, or by using :term:`generators <generator>`.
13The :keyword:`async def` type of coroutine was added in Python 3.5, and
14is recommended if there is no need to support older Python versions.
Victor Stinnerea3183f2013-12-03 01:08:00 +010015
Yury Selivanov66f88282015-06-24 11:04:15 -040016Generator-based coroutines should be decorated with :func:`@asyncio.coroutine
17<asyncio.coroutine>`, although this is not strictly enforced.
18The decorator enables compatibility with :keyword:`async def` coroutines,
19and also serves as documentation. Generator-based
20coroutines use the ``yield from`` syntax introduced in :pep:`380`,
Victor Stinnerea3183f2013-12-03 01:08:00 +010021instead of the original ``yield`` syntax.
22
23The word "coroutine", like the word "generator", is used for two
24different (though related) concepts:
25
Yury Selivanov66f88282015-06-24 11:04:15 -040026- The function that defines a coroutine
27 (a function definition using :keyword:`async def` or
Victor Stinner59759ff2014-01-16 19:30:21 +010028 decorated with ``@asyncio.coroutine``). If disambiguation is needed
Victor Stinner1ad5afc2014-01-30 00:18:50 +010029 we will call this a *coroutine function* (:func:`iscoroutinefunction`
30 returns ``True``).
Victor Stinnerea3183f2013-12-03 01:08:00 +010031
32- The object obtained by calling a coroutine function. This object
33 represents a computation or an I/O operation (usually a combination)
34 that will complete eventually. If disambiguation is needed we will
Victor Stinner1ad5afc2014-01-30 00:18:50 +010035 call it a *coroutine object* (:func:`iscoroutine` returns ``True``).
Victor Stinnerea3183f2013-12-03 01:08:00 +010036
37Things a coroutine can do:
38
Yury Selivanov66f88282015-06-24 11:04:15 -040039- ``result = await future`` or ``result = yield from future`` --
40 suspends the coroutine until the
Victor Stinnerea3183f2013-12-03 01:08:00 +010041 future is done, then returns the future's result, or raises an
42 exception, which will be propagated. (If the future is cancelled,
43 it will raise a ``CancelledError`` exception.) Note that tasks are
44 futures, and everything said about futures also applies to tasks.
45
Yury Selivanov66f88282015-06-24 11:04:15 -040046- ``result = await coroutine`` or ``result = yield from coroutine`` --
47 wait for another coroutine to
Victor Stinnerea3183f2013-12-03 01:08:00 +010048 produce a result (or raise an exception, which will be propagated).
49 The ``coroutine`` expression must be a *call* to another coroutine.
50
51- ``return expression`` -- produce a result to the coroutine that is
Yury Selivanov66f88282015-06-24 11:04:15 -040052 waiting for this one using :keyword:`await` or ``yield from``.
Victor Stinnerea3183f2013-12-03 01:08:00 +010053
54- ``raise exception`` -- raise an exception in the coroutine that is
Yury Selivanov66f88282015-06-24 11:04:15 -040055 waiting for this one using :keyword:`await` or ``yield from``.
Victor Stinnerea3183f2013-12-03 01:08:00 +010056
Yury Selivanov66f88282015-06-24 11:04:15 -040057Calling a coroutine does not start its code running --
58the coroutine object returned by the call doesn't do anything until you
59schedule its execution. There are two basic ways to start it running:
60call ``await coroutine`` or ``yield from coroutine`` from another coroutine
Victor Stinner530ef2f2014-07-08 12:39:10 +020061(assuming the other coroutine is already running!), or schedule its execution
Guido van Rossumf68afd82016-08-08 09:41:21 -070062using the :func:`ensure_future` function or the :meth:`AbstractEventLoop.create_task`
Victor Stinner337e03f2014-08-11 01:11:13 +020063method.
64
Victor Stinnerea3183f2013-12-03 01:08:00 +010065
66Coroutines (and tasks) can only run when the event loop is running.
67
Victor Stinnerdb39a0d2014-01-16 18:58:01 +010068.. decorator:: coroutine
69
Yury Selivanov66f88282015-06-24 11:04:15 -040070 Decorator to mark generator-based coroutines. This enables
71 the generator use :keyword:`!yield from` to call :keyword:`async
72 def` coroutines, and also enables the generator to be called by
73 :keyword:`async def` coroutines, for instance using an
74 :keyword:`await` expression.
Victor Stinnerdb39a0d2014-01-16 18:58:01 +010075
Yury Selivanov66f88282015-06-24 11:04:15 -040076 There is no need to decorate :keyword:`async def` coroutines themselves.
77
78 If the generator is not yielded from before it is destroyed, an error
Victor Stinnerdb39a0d2014-01-16 18:58:01 +010079 message is logged. See :ref:`Detect coroutines never scheduled
80 <asyncio-coroutine-not-scheduled>`.
81
Yury Selivanov37f15bc2014-02-20 16:20:44 -050082.. note::
83
84 In this documentation, some methods are documented as coroutines,
85 even if they are plain Python functions returning a :class:`Future`.
86 This is intentional to have a freedom of tweaking the implementation
87 of these functions in the future. If such a function is needed to be
Yury Selivanov04356e12015-06-30 22:13:22 -040088 used in a callback-style code, wrap its result with :func:`ensure_future`.
Yury Selivanov37f15bc2014-02-20 16:20:44 -050089
Victor Stinnerea3183f2013-12-03 01:08:00 +010090
Victor Stinnerb69d62d2013-12-10 02:09:46 +010091.. _asyncio-hello-world-coroutine:
92
Victor Stinner7f314ed2014-10-15 18:49:16 +020093Example: Hello World coroutine
94^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinnerb69d62d2013-12-10 02:09:46 +010095
Victor Stinner7f314ed2014-10-15 18:49:16 +020096Example of coroutine displaying ``"Hello World"``::
Victor Stinnerb69d62d2013-12-10 02:09:46 +010097
98 import asyncio
99
Yury Selivanov66f88282015-06-24 11:04:15 -0400100 async def hello_world():
Victor Stinner7f314ed2014-10-15 18:49:16 +0200101 print("Hello World!")
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100102
103 loop = asyncio.get_event_loop()
Victor Stinner7f314ed2014-10-15 18:49:16 +0200104 # Blocking call which returns when the hello_world() coroutine is done
105 loop.run_until_complete(hello_world())
106 loop.close()
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100107
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100108.. seealso::
109
Victor Stinner7f314ed2014-10-15 18:49:16 +0200110 The :ref:`Hello World with call_soon() <asyncio-hello-world-callback>`
Guido van Rossumf68afd82016-08-08 09:41:21 -0700111 example uses the :meth:`AbstractEventLoop.call_soon` method to schedule a
Victor Stinner7f314ed2014-10-15 18:49:16 +0200112 callback.
113
114
115.. _asyncio-date-coroutine:
116
117Example: Coroutine displaying the current date
118^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
119
120Example of coroutine displaying the current date every second during 5 seconds
121using the :meth:`sleep` function::
122
123 import asyncio
124 import datetime
125
Yury Selivanov66f88282015-06-24 11:04:15 -0400126 async def display_date(loop):
127 end_time = loop.time() + 5.0
128 while True:
129 print(datetime.datetime.now())
130 if (loop.time() + 1.0) >= end_time:
131 break
132 await asyncio.sleep(1)
133
134 loop = asyncio.get_event_loop()
135 # Blocking call which returns when the display_date() coroutine is done
136 loop.run_until_complete(display_date(loop))
137 loop.close()
138
Victor Stinner7f314ed2014-10-15 18:49:16 +0200139.. seealso::
140
141 The :ref:`display the current date with call_later()
142 <asyncio-date-callback>` example uses a callback with the
Guido van Rossumf68afd82016-08-08 09:41:21 -0700143 :meth:`AbstractEventLoop.call_later` method.
Victor Stinner7f314ed2014-10-15 18:49:16 +0200144
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100145
146Example: Chain coroutines
147^^^^^^^^^^^^^^^^^^^^^^^^^
148
149Example chaining coroutines::
150
151 import asyncio
152
Yury Selivanov66f88282015-06-24 11:04:15 -0400153 async def compute(x, y):
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100154 print("Compute %s + %s ..." % (x, y))
Yury Selivanov66f88282015-06-24 11:04:15 -0400155 await asyncio.sleep(1.0)
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100156 return x + y
157
Yury Selivanov66f88282015-06-24 11:04:15 -0400158 async def print_sum(x, y):
159 result = await compute(x, y)
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100160 print("%s + %s = %s" % (x, y, result))
161
162 loop = asyncio.get_event_loop()
163 loop.run_until_complete(print_sum(1, 2))
Victor Stinnerf40c6632014-01-28 23:32:40 +0100164 loop.close()
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100165
166``compute()`` is chained to ``print_sum()``: ``print_sum()`` coroutine waits
Brian Curtina1afeec2014-02-08 18:36:14 -0600167until ``compute()`` is completed before returning its result.
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100168
Victor Stinner1c4b8922013-12-12 12:35:17 +0100169Sequence diagram of the example:
170
171.. image:: tulip_coro.png
172 :align: center
173
Guido van Rossumf68afd82016-08-08 09:41:21 -0700174The "Task" is created by the :meth:`AbstractEventLoop.run_until_complete` method
Victor Stinner59759ff2014-01-16 19:30:21 +0100175when it gets a coroutine object instead of a task.
Victor Stinner86e139a2013-12-13 12:51:24 +0100176
177The diagram shows the control flow, it does not describe exactly how things
178work internally. For example, the sleep coroutine creates an internal future
Guido van Rossumf68afd82016-08-08 09:41:21 -0700179which uses :meth:`AbstractEventLoop.call_later` to wake up the task in 1 second.
Victor Stinner1c4b8922013-12-12 12:35:17 +0100180
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100181
Victor Stinner99c2ab42013-12-03 19:17:25 +0100182InvalidStateError
183-----------------
184
185.. exception:: InvalidStateError
186
187 The operation is not allowed in this state.
188
189
Victor Stinner28d0ae482014-05-29 00:04:57 +0200190TimeoutError
191------------
192
193.. exception:: TimeoutError
194
195 The operation exceeded the given deadline.
196
197.. note::
198
199 This exception is different from the builtin :exc:`TimeoutError` exception!
200
201
Victor Stinner99c2ab42013-12-03 19:17:25 +0100202Future
203------
204
205.. class:: Future(\*, loop=None)
206
207 This class is *almost* compatible with :class:`concurrent.futures.Future`.
208
209 Differences:
210
211 - :meth:`result` and :meth:`exception` do not take a timeout argument and
212 raise an exception when the future isn't done yet.
213
214 - Callbacks registered with :meth:`add_done_callback` are always called
Guido van Rossumf68afd82016-08-08 09:41:21 -0700215 via the event loop's :meth:`~AbstractEventLoop.call_soon_threadsafe`.
Victor Stinner99c2ab42013-12-03 19:17:25 +0100216
217 - This class is not compatible with the :func:`~concurrent.futures.wait` and
218 :func:`~concurrent.futures.as_completed` functions in the
219 :mod:`concurrent.futures` package.
220
Victor Stinner83704962015-02-25 14:24:15 +0100221 This class is :ref:`not thread safe <asyncio-multithreading>`.
222
Victor Stinner99c2ab42013-12-03 19:17:25 +0100223 .. method:: cancel()
224
225 Cancel the future and schedule callbacks.
226
227 If the future is already done or cancelled, return ``False``. Otherwise,
228 change the future's state to cancelled, schedule the callbacks and return
229 ``True``.
230
231 .. method:: cancelled()
232
233 Return ``True`` if the future was cancelled.
234
235 .. method:: done()
236
Serhiy Storchaka4adf01c2016-10-19 18:30:05 +0300237 Return ``True`` if the future is done.
Victor Stinner99c2ab42013-12-03 19:17:25 +0100238
239 Done means either that a result / exception are available, or that the
240 future was cancelled.
241
242 .. method:: result()
243
244 Return the result this future represents.
245
246 If the future has been cancelled, raises :exc:`CancelledError`. If the
247 future's result isn't yet available, raises :exc:`InvalidStateError`. If
248 the future is done and has an exception set, this exception is raised.
249
250 .. method:: exception()
251
252 Return the exception that was set on this future.
253
254 The exception (or ``None`` if no exception was set) is returned only if
255 the future is done. If the future has been cancelled, raises
256 :exc:`CancelledError`. If the future isn't done yet, raises
257 :exc:`InvalidStateError`.
258
259 .. method:: add_done_callback(fn)
260
261 Add a callback to be run when the future becomes done.
262
263 The callback is called with a single argument - the future object. If the
264 future is already done when this is called, the callback is scheduled
Guido van Rossumf68afd82016-08-08 09:41:21 -0700265 with :meth:`~AbstractEventLoop.call_soon`.
Victor Stinner99c2ab42013-12-03 19:17:25 +0100266
Victor Stinner8464c242014-11-28 13:15:41 +0100267 :ref:`Use functools.partial to pass parameters to the callback
268 <asyncio-pass-keywords>`. For example,
269 ``fut.add_done_callback(functools.partial(print, "Future:",
270 flush=True))`` will call ``print("Future:", fut, flush=True)``.
271
Victor Stinner99c2ab42013-12-03 19:17:25 +0100272 .. method:: remove_done_callback(fn)
273
274 Remove all instances of a callback from the "call when done" list.
275
276 Returns the number of callbacks removed.
277
278 .. method:: set_result(result)
279
280 Mark the future done and set its result.
281
282 If the future is already done when this method is called, raises
283 :exc:`InvalidStateError`.
284
285 .. method:: set_exception(exception)
286
287 Mark the future done and set an exception.
288
289 If the future is already done when this method is called, raises
290 :exc:`InvalidStateError`.
291
292
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100293Example: Future with run_until_complete()
294^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
295
Victor Stinner59759ff2014-01-16 19:30:21 +0100296Example combining a :class:`Future` and a :ref:`coroutine function
297<coroutine>`::
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100298
299 import asyncio
300
Berker Peksagf5928672017-02-07 11:27:09 +0300301 async def slow_operation(future):
302 await asyncio.sleep(1)
Victor Stinner04e05da2014-02-17 10:54:30 +0100303 future.set_result('Future is done!')
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100304
305 loop = asyncio.get_event_loop()
306 future = asyncio.Future()
Yury Selivanovd7e19bb2015-05-11 16:33:41 -0400307 asyncio.ensure_future(slow_operation(future))
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100308 loop.run_until_complete(future)
309 print(future.result())
Victor Stinnerf40c6632014-01-28 23:32:40 +0100310 loop.close()
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100311
Terry Jan Reedyc935a952014-07-24 02:33:14 -0400312The coroutine function is responsible for the computation (which takes 1 second)
Victor Stinner59759ff2014-01-16 19:30:21 +0100313and it stores the result into the future. The
Guido van Rossumf68afd82016-08-08 09:41:21 -0700314:meth:`~AbstractEventLoop.run_until_complete` method waits for the completion of
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100315the future.
316
317.. note::
Guido van Rossumf68afd82016-08-08 09:41:21 -0700318 The :meth:`~AbstractEventLoop.run_until_complete` method uses internally the
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100319 :meth:`~Future.add_done_callback` method to be notified when the future is
320 done.
321
322
323Example: Future with run_forever()
324^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
325
326The previous example can be written differently using the
327:meth:`Future.add_done_callback` method to describe explicitly the control
328flow::
329
330 import asyncio
331
Berker Peksagf5928672017-02-07 11:27:09 +0300332 async def slow_operation(future):
333 await asyncio.sleep(1)
Victor Stinner04e05da2014-02-17 10:54:30 +0100334 future.set_result('Future is done!')
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100335
336 def got_result(future):
337 print(future.result())
338 loop.stop()
339
340 loop = asyncio.get_event_loop()
341 future = asyncio.Future()
Yury Selivanovd7e19bb2015-05-11 16:33:41 -0400342 asyncio.ensure_future(slow_operation(future))
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100343 future.add_done_callback(got_result)
Victor Stinner04e05da2014-02-17 10:54:30 +0100344 try:
345 loop.run_forever()
346 finally:
347 loop.close()
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100348
Victor Stinner039f7032014-12-02 17:52:45 +0100349In this example, the future is used to link ``slow_operation()`` to
350``got_result()``: when ``slow_operation()`` is done, ``got_result()`` is called
351with the result.
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100352
353
Victor Stinnerea3183f2013-12-03 01:08:00 +0100354Task
355----
356
357.. class:: Task(coro, \*, loop=None)
358
Victor Stinner530ef2f2014-07-08 12:39:10 +0200359 Schedule the execution of a :ref:`coroutine <coroutine>`: wrap it in a
360 future. A task is a subclass of :class:`Future`.
361
R David Murray22dd8332014-09-24 11:09:09 -0400362 A task is responsible for executing a coroutine object in an event loop. If
Victor Stinner530ef2f2014-07-08 12:39:10 +0200363 the wrapped coroutine yields from a future, the task suspends the execution
Berker Peksag002b0a72016-10-04 20:45:47 +0300364 of the wrapped coroutine and waits for the completion of the future. When
Victor Stinner530ef2f2014-07-08 12:39:10 +0200365 the future is done, the execution of the wrapped coroutine restarts with the
366 result or the exception of the future.
367
368 Event loops use cooperative scheduling: an event loop only runs one task at
R David Murray22dd8332014-09-24 11:09:09 -0400369 a time. Other tasks may run in parallel if other event loops are
Victor Stinner530ef2f2014-07-08 12:39:10 +0200370 running in different threads. While a task waits for the completion of a
371 future, the event loop executes a new task.
372
Andrew Svetlovf1240162016-01-11 14:40:35 +0200373 The cancellation of a task is different from the cancelation of a
374 future. Calling :meth:`cancel` will throw a
375 :exc:`~concurrent.futures.CancelledError` to the wrapped
376 coroutine. :meth:`~Future.cancelled` only returns ``True`` if the
Victor Stinner530ef2f2014-07-08 12:39:10 +0200377 wrapped coroutine did not catch the
378 :exc:`~concurrent.futures.CancelledError` exception, or raised a
379 :exc:`~concurrent.futures.CancelledError` exception.
380
381 If a pending task is destroyed, the execution of its wrapped :ref:`coroutine
382 <coroutine>` did not complete. It is probably a bug and a warning is
383 logged: see :ref:`Pending task destroyed <asyncio-pending-task-destroyed>`.
384
Yury Selivanov04356e12015-06-30 22:13:22 -0400385 Don't directly create :class:`Task` instances: use the :func:`ensure_future`
Guido van Rossumf68afd82016-08-08 09:41:21 -0700386 function or the :meth:`AbstractEventLoop.create_task` method.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100387
Victor Stinner83704962015-02-25 14:24:15 +0100388 This class is :ref:`not thread safe <asyncio-multithreading>`.
389
Victor Stinnerea3183f2013-12-03 01:08:00 +0100390 .. classmethod:: all_tasks(loop=None)
391
392 Return a set of all tasks for an event loop.
393
394 By default all tasks for the current event loop are returned.
395
Victor Stinner742520b2013-12-10 12:14:50 +0100396 .. classmethod:: current_task(loop=None)
397
398 Return the currently running task in an event loop or ``None``.
399
400 By default the current task for the current event loop is returned.
401
402 ``None`` is returned when called not in the context of a :class:`Task`.
403
Victor Stinner8d213572014-06-02 23:06:46 +0200404 .. method:: cancel()
405
R David Murray22dd8332014-09-24 11:09:09 -0400406 Request that this task cancel itself.
Victor Stinner8d213572014-06-02 23:06:46 +0200407
408 This arranges for a :exc:`~concurrent.futures.CancelledError` to be
409 thrown into the wrapped coroutine on the next cycle through the event
410 loop. The coroutine then has a chance to clean up or even deny the
411 request using try/except/finally.
412
R David Murray22dd8332014-09-24 11:09:09 -0400413 Unlike :meth:`Future.cancel`, this does not guarantee that the task
Victor Stinner8d213572014-06-02 23:06:46 +0200414 will be cancelled: the exception might be caught and acted upon, delaying
R David Murray22dd8332014-09-24 11:09:09 -0400415 cancellation of the task or preventing cancellation completely. The task
416 may also return a value or raise a different exception.
Victor Stinner8d213572014-06-02 23:06:46 +0200417
418 Immediately after this method is called, :meth:`~Future.cancelled` will
419 not return ``True`` (unless the task was already cancelled). A task will
420 be marked as cancelled when the wrapped coroutine terminates with a
421 :exc:`~concurrent.futures.CancelledError` exception (even if
422 :meth:`cancel` was not called).
423
424 .. method:: get_stack(\*, limit=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100425
426 Return the list of stack frames for this task's coroutine.
427
Andrew Svetlovf1240162016-01-11 14:40:35 +0200428 If the coroutine is not done, this returns the stack where it is
429 suspended. If the coroutine has completed successfully or was
430 cancelled, this returns an empty list. If the coroutine was
431 terminated by an exception, this returns the list of traceback
432 frames.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100433
434 The frames are always ordered from oldest to newest.
435
Brian Curtina1afeec2014-02-08 18:36:14 -0600436 The optional limit gives the maximum number of frames to return; by
Victor Stinnerea3183f2013-12-03 01:08:00 +0100437 default all available frames are returned. Its meaning differs depending
438 on whether a stack or a traceback is returned: the newest frames of a
439 stack are returned, but the oldest frames of a traceback are returned.
440 (This matches the behavior of the traceback module.)
441
442 For reasons beyond our control, only one stack frame is returned for a
443 suspended coroutine.
444
445 .. method:: print_stack(\*, limit=None, file=None)
446
447 Print the stack or traceback for this task's coroutine.
448
449 This produces output similar to that of the traceback module, for the
450 frames retrieved by get_stack(). The limit argument is passed to
451 get_stack(). The file argument is an I/O stream to which the output
R David Murray22dd8332014-09-24 11:09:09 -0400452 is written; by default output is written to sys.stderr.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100453
454
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100455Example: Parallel execution of tasks
456^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
457
458Example executing 3 tasks (A, B, C) in parallel::
459
460 import asyncio
461
Berker Peksagd5adb632017-02-01 22:37:16 +0300462 async def factorial(name, number):
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100463 f = 1
Victor Stinner34f29462013-12-10 02:51:05 +0100464 for i in range(2, number+1):
465 print("Task %s: Compute factorial(%s)..." % (name, i))
Berker Peksagd5adb632017-02-01 22:37:16 +0300466 await asyncio.sleep(1)
Victor Stinner34f29462013-12-10 02:51:05 +0100467 f *= i
468 print("Task %s: factorial(%s) = %s" % (name, number, f))
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100469
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100470 loop = asyncio.get_event_loop()
Berker Peksagd5adb632017-02-01 22:37:16 +0300471 loop.run_until_complete(asyncio.gather(
472 factorial("A", 2),
473 factorial("B", 3),
474 factorial("C", 4),
475 ))
Victor Stinnerf40c6632014-01-28 23:32:40 +0100476 loop.close()
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100477
478Output::
479
Victor Stinner34f29462013-12-10 02:51:05 +0100480 Task A: Compute factorial(2)...
481 Task B: Compute factorial(2)...
482 Task C: Compute factorial(2)...
483 Task A: factorial(2) = 2
484 Task B: Compute factorial(3)...
485 Task C: Compute factorial(3)...
486 Task B: factorial(3) = 6
487 Task C: Compute factorial(4)...
488 Task C: factorial(4) = 24
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100489
Victor Stinner34f29462013-12-10 02:51:05 +0100490A task is automatically scheduled for execution when it is created. The event
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100491loop stops when all tasks are done.
492
493
Victor Stinnerea3183f2013-12-03 01:08:00 +0100494Task functions
495--------------
496
Eli Bendersky029981b2014-01-20 07:02:22 -0800497.. note::
498
Martin Panterc04fb562016-02-10 05:44:01 +0000499 In the functions below, the optional *loop* argument allows explicitly setting
Eli Bendersky029981b2014-01-20 07:02:22 -0800500 the event loop object used by the underlying task or coroutine. If it's
501 not provided, the default event loop is used.
502
Victor Stinner99c2ab42013-12-03 19:17:25 +0100503.. function:: as_completed(fs, \*, loop=None, timeout=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100504
Victor Stinner99c2ab42013-12-03 19:17:25 +0100505 Return an iterator whose values, when waited for, are :class:`Future`
506 instances.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100507
Victor Stinner28d0ae482014-05-29 00:04:57 +0200508 Raises :exc:`asyncio.TimeoutError` if the timeout occurs before all Futures
509 are done.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100510
511 Example::
512
513 for f in as_completed(fs):
514 result = yield from f # The 'yield from' may raise
515 # Use result
516
517 .. note::
518
519 The futures ``f`` are not necessarily members of fs.
520
Yury Selivanovd7e19bb2015-05-11 16:33:41 -0400521.. function:: ensure_future(coro_or_future, \*, loop=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100522
Victor Stinner980dd842014-10-12 21:36:17 +0200523 Schedule the execution of a :ref:`coroutine object <coroutine>`: wrap it in
524 a future. Return a :class:`Task` object.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100525
Victor Stinner99c2ab42013-12-03 19:17:25 +0100526 If the argument is a :class:`Future`, it is returned directly.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100527
Yury Selivanovd7e19bb2015-05-11 16:33:41 -0400528 .. versionadded:: 3.4.4
529
Yury Selivanove319ab02015-12-15 00:45:24 -0500530 .. versionchanged:: 3.5.1
531 The function accepts any :term:`awaitable` object.
532
Victor Stinner337e03f2014-08-11 01:11:13 +0200533 .. seealso::
534
Guido van Rossumf68afd82016-08-08 09:41:21 -0700535 The :meth:`AbstractEventLoop.create_task` method.
Victor Stinner337e03f2014-08-11 01:11:13 +0200536
Yury Selivanovd7e19bb2015-05-11 16:33:41 -0400537.. function:: async(coro_or_future, \*, loop=None)
538
539 A deprecated alias to :func:`ensure_future`.
540
541 .. deprecated:: 3.4.4
542
adisbladis824f6872017-06-09 14:28:59 +0800543.. function:: wrap_future(future, \*, loop=None)
544
545 Wrap a :class:`concurrent.futures.Future` object in a :class:`Future`
546 object.
547
Victor Stinner99c2ab42013-12-03 19:17:25 +0100548.. function:: gather(\*coros_or_futures, loop=None, return_exceptions=False)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100549
Victor Stinner59759ff2014-01-16 19:30:21 +0100550 Return a future aggregating results from the given coroutine objects or
551 futures.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100552
553 All futures must share the same event loop. If all the tasks are done
554 successfully, the returned future's result is the list of results (in the
555 order of the original sequence, not necessarily the order of results
Serhiy Storchaka4adf01c2016-10-19 18:30:05 +0300556 arrival). If *return_exceptions* is true, exceptions in the tasks are
Victor Stinnerea3183f2013-12-03 01:08:00 +0100557 treated the same as successful results, and gathered in the result list;
558 otherwise, the first raised exception will be immediately propagated to the
559 returned future.
560
561 Cancellation: if the outer Future is cancelled, all children (that have not
562 completed yet) are also cancelled. If any child is cancelled, this is
563 treated as if it raised :exc:`~concurrent.futures.CancelledError` -- the
564 outer Future is *not* cancelled in this case. (This is to prevent the
565 cancellation of one child to cause other children to be cancelled.)
566
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100567.. function:: iscoroutine(obj)
568
Yury Selivanov66f88282015-06-24 11:04:15 -0400569 Return ``True`` if *obj* is a :ref:`coroutine object <coroutine>`,
570 which may be based on a generator or an :keyword:`async def` coroutine.
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100571
Yury Selivanov66f88282015-06-24 11:04:15 -0400572.. function:: iscoroutinefunction(func)
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100573
Yury Selivanov66f88282015-06-24 11:04:15 -0400574 Return ``True`` if *func* is determined to be a :ref:`coroutine function
575 <coroutine>`, which may be a decorated generator function or an
576 :keyword:`async def` function.
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100577
Andrew Svetlovf1240162016-01-11 14:40:35 +0200578.. function:: run_coroutine_threadsafe(coro, loop)
579
580 Submit a :ref:`coroutine object <coroutine>` to a given event loop.
581
582 Return a :class:`concurrent.futures.Future` to access the result.
583
584 This function is meant to be called from a different thread than the one
585 where the event loop is running. Usage::
586
587 # Create a coroutine
588 coro = asyncio.sleep(1, result=3)
589 # Submit the coroutine to a given loop
590 future = asyncio.run_coroutine_threadsafe(coro, loop)
591 # Wait for the result with an optional timeout argument
592 assert future.result(timeout) == 3
593
594 If an exception is raised in the coroutine, the returned future will be
595 notified. It can also be used to cancel the task in the event loop::
596
597 try:
598 result = future.result(timeout)
599 except asyncio.TimeoutError:
600 print('The coroutine took too long, cancelling the task...')
601 future.cancel()
602 except Exception as exc:
603 print('The coroutine raised an exception: {!r}'.format(exc))
604 else:
605 print('The coroutine returned: {!r}'.format(result))
606
607 See the :ref:`concurrency and multithreading <asyncio-multithreading>`
608 section of the documentation.
609
610 .. note::
611
Andrew Svetlov3af81f22016-01-11 14:45:25 +0200612 Unlike other functions from the module,
613 :func:`run_coroutine_threadsafe` requires the *loop* argument to
Zachary Waref9aff922016-06-01 00:01:10 -0500614 be passed explicitly.
Andrew Svetlovf1240162016-01-11 14:40:35 +0200615
Andrew Svetlovea471342016-01-11 15:41:43 +0200616 .. versionadded:: 3.5.1
Andrew Svetlovf1240162016-01-11 14:40:35 +0200617
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100618.. coroutinefunction:: sleep(delay, result=None, \*, loop=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100619
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500620 Create a :ref:`coroutine <coroutine>` that completes after a given
Eli Bendersky2d26af82014-01-20 06:59:23 -0800621 time (in seconds). If *result* is provided, it is produced to the caller
622 when the coroutine completes.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100623
Victor Stinner45b27ed2014-02-01 02:36:43 +0100624 The resolution of the sleep depends on the :ref:`granularity of the event
625 loop <asyncio-delayed-calls>`.
626
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100627 This function is a :ref:`coroutine <coroutine>`.
628
Victor Stinnerea3183f2013-12-03 01:08:00 +0100629.. function:: shield(arg, \*, loop=None)
630
631 Wait for a future, shielding it from cancellation.
632
633 The statement::
634
635 res = yield from shield(something())
636
637 is exactly equivalent to the statement::
638
639 res = yield from something()
640
641 *except* that if the coroutine containing it is cancelled, the task running
642 in ``something()`` is not cancelled. From the point of view of
643 ``something()``, the cancellation did not happen. But its caller is still
644 cancelled, so the yield-from expression still raises
645 :exc:`~concurrent.futures.CancelledError`. Note: If ``something()`` is
646 cancelled by other means this will still cancel ``shield()``.
647
648 If you want to completely ignore cancellation (not recommended) you can
649 combine ``shield()`` with a try/except clause, as follows::
650
651 try:
652 res = yield from shield(something())
653 except CancelledError:
654 res = None
655
Yury Selivanov950204d2016-05-16 16:23:00 -0400656
Andrew Svetlovf1240162016-01-11 14:40:35 +0200657.. coroutinefunction:: wait(futures, \*, loop=None, timeout=None,\
658 return_when=ALL_COMPLETED)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100659
Victor Stinner59759ff2014-01-16 19:30:21 +0100660 Wait for the Futures and coroutine objects given by the sequence *futures*
661 to complete. Coroutines will be wrapped in Tasks. Returns two sets of
Victor Stinner99c2ab42013-12-03 19:17:25 +0100662 :class:`Future`: (done, pending).
Victor Stinnerea3183f2013-12-03 01:08:00 +0100663
Victor Stinnerdb74d982014-06-10 11:16:05 +0200664 The sequence *futures* must not be empty.
665
Victor Stinnerea3183f2013-12-03 01:08:00 +0100666 *timeout* can be used to control the maximum number of seconds to wait before
667 returning. *timeout* can be an int or float. If *timeout* is not specified
668 or ``None``, there is no limit to the wait time.
669
670 *return_when* indicates when this function should return. It must be one of
Victor Stinner933a8c82013-12-03 01:59:38 +0100671 the following constants of the :mod:`concurrent.futures` module:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100672
673 .. tabularcolumns:: |l|L|
674
675 +-----------------------------+----------------------------------------+
676 | Constant | Description |
677 +=============================+========================================+
678 | :const:`FIRST_COMPLETED` | The function will return when any |
679 | | future finishes or is cancelled. |
680 +-----------------------------+----------------------------------------+
681 | :const:`FIRST_EXCEPTION` | The function will return when any |
682 | | future finishes by raising an |
683 | | exception. If no future raises an |
684 | | exception then it is equivalent to |
685 | | :const:`ALL_COMPLETED`. |
686 +-----------------------------+----------------------------------------+
687 | :const:`ALL_COMPLETED` | The function will return when all |
688 | | futures finish or are cancelled. |
689 +-----------------------------+----------------------------------------+
690
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500691 This function is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100692
693 Usage::
694
695 done, pending = yield from asyncio.wait(fs)
696
697 .. note::
698
Victor Stinner28d0ae482014-05-29 00:04:57 +0200699 This does not raise :exc:`asyncio.TimeoutError`! Futures that aren't done
700 when the timeout occurs are returned in the second set.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100701
Victor Stinner3e09e322013-12-03 01:22:06 +0100702
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100703.. coroutinefunction:: wait_for(fut, timeout, \*, loop=None)
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100704
705 Wait for the single :class:`Future` or :ref:`coroutine object <coroutine>`
Victor Stinner530ef2f2014-07-08 12:39:10 +0200706 to complete with timeout. If *timeout* is ``None``, block until the future
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100707 completes.
708
Victor Stinner337e03f2014-08-11 01:11:13 +0200709 Coroutine will be wrapped in :class:`Task`.
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100710
711 Returns result of the Future or coroutine. When a timeout occurs, it
Victor Stinner28d0ae482014-05-29 00:04:57 +0200712 cancels the task and raises :exc:`asyncio.TimeoutError`. To avoid the task
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100713 cancellation, wrap it in :func:`shield`.
714
Victor Stinner72dcb0a2015-04-03 17:08:19 +0200715 If the wait is cancelled, the future *fut* is also cancelled.
716
Victor Stinner530ef2f2014-07-08 12:39:10 +0200717 This function is a :ref:`coroutine <coroutine>`, usage::
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500718
Victor Stinner530ef2f2014-07-08 12:39:10 +0200719 result = yield from asyncio.wait_for(fut, 60.0)
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100720
Victor Stinner72dcb0a2015-04-03 17:08:19 +0200721 .. versionchanged:: 3.4.3
722 If the wait is cancelled, the future *fut* is now also cancelled.