blob: ff35b0add9d694febe817e1a8d8e5396944f78b4 [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
lf627d2c82017-07-25 17:03:51 -06006**Source code:** :source:`Lib/asyncio/tasks.py`
7
8**Source code:** :source:`Lib/asyncio/coroutines.py`
9
Victor Stinnerea3183f2013-12-03 01:08:00 +010010.. _coroutine:
11
12Coroutines
13----------
14
Yury Selivanov66f88282015-06-24 11:04:15 -040015Coroutines used with :mod:`asyncio` may be implemented using the
16:keyword:`async def` statement, or by using :term:`generators <generator>`.
17The :keyword:`async def` type of coroutine was added in Python 3.5, and
18is recommended if there is no need to support older Python versions.
Victor Stinnerea3183f2013-12-03 01:08:00 +010019
Yury Selivanov66f88282015-06-24 11:04:15 -040020Generator-based coroutines should be decorated with :func:`@asyncio.coroutine
21<asyncio.coroutine>`, although this is not strictly enforced.
22The decorator enables compatibility with :keyword:`async def` coroutines,
23and also serves as documentation. Generator-based
24coroutines use the ``yield from`` syntax introduced in :pep:`380`,
Victor Stinnerea3183f2013-12-03 01:08:00 +010025instead of the original ``yield`` syntax.
26
27The word "coroutine", like the word "generator", is used for two
28different (though related) concepts:
29
Yury Selivanov66f88282015-06-24 11:04:15 -040030- The function that defines a coroutine
31 (a function definition using :keyword:`async def` or
Victor Stinner59759ff2014-01-16 19:30:21 +010032 decorated with ``@asyncio.coroutine``). If disambiguation is needed
Victor Stinner1ad5afc2014-01-30 00:18:50 +010033 we will call this a *coroutine function* (:func:`iscoroutinefunction`
34 returns ``True``).
Victor Stinnerea3183f2013-12-03 01:08:00 +010035
36- The object obtained by calling a coroutine function. This object
37 represents a computation or an I/O operation (usually a combination)
38 that will complete eventually. If disambiguation is needed we will
Victor Stinner1ad5afc2014-01-30 00:18:50 +010039 call it a *coroutine object* (:func:`iscoroutine` returns ``True``).
Victor Stinnerea3183f2013-12-03 01:08:00 +010040
41Things a coroutine can do:
42
Yury Selivanov66f88282015-06-24 11:04:15 -040043- ``result = await future`` or ``result = yield from future`` --
44 suspends the coroutine until the
Victor Stinnerea3183f2013-12-03 01:08:00 +010045 future is done, then returns the future's result, or raises an
46 exception, which will be propagated. (If the future is cancelled,
47 it will raise a ``CancelledError`` exception.) Note that tasks are
48 futures, and everything said about futures also applies to tasks.
49
Yury Selivanov66f88282015-06-24 11:04:15 -040050- ``result = await coroutine`` or ``result = yield from coroutine`` --
51 wait for another coroutine to
Victor Stinnerea3183f2013-12-03 01:08:00 +010052 produce a result (or raise an exception, which will be propagated).
53 The ``coroutine`` expression must be a *call* to another coroutine.
54
55- ``return expression`` -- produce a result to the coroutine that is
Yury Selivanov66f88282015-06-24 11:04:15 -040056 waiting for this one using :keyword:`await` or ``yield from``.
Victor Stinnerea3183f2013-12-03 01:08:00 +010057
58- ``raise exception`` -- raise an exception in the coroutine that is
Yury Selivanov66f88282015-06-24 11:04:15 -040059 waiting for this one using :keyword:`await` or ``yield from``.
Victor Stinnerea3183f2013-12-03 01:08:00 +010060
Yury Selivanov66f88282015-06-24 11:04:15 -040061Calling a coroutine does not start its code running --
62the coroutine object returned by the call doesn't do anything until you
63schedule its execution. There are two basic ways to start it running:
64call ``await coroutine`` or ``yield from coroutine`` from another coroutine
Victor Stinner530ef2f2014-07-08 12:39:10 +020065(assuming the other coroutine is already running!), or schedule its execution
Guido van Rossumf68afd82016-08-08 09:41:21 -070066using the :func:`ensure_future` function or the :meth:`AbstractEventLoop.create_task`
Victor Stinner337e03f2014-08-11 01:11:13 +020067method.
68
Victor Stinnerea3183f2013-12-03 01:08:00 +010069
70Coroutines (and tasks) can only run when the event loop is running.
71
Victor Stinnerdb39a0d2014-01-16 18:58:01 +010072.. decorator:: coroutine
73
Yury Selivanov66f88282015-06-24 11:04:15 -040074 Decorator to mark generator-based coroutines. This enables
75 the generator use :keyword:`!yield from` to call :keyword:`async
76 def` coroutines, and also enables the generator to be called by
77 :keyword:`async def` coroutines, for instance using an
78 :keyword:`await` expression.
Victor Stinnerdb39a0d2014-01-16 18:58:01 +010079
Yury Selivanov66f88282015-06-24 11:04:15 -040080 There is no need to decorate :keyword:`async def` coroutines themselves.
81
82 If the generator is not yielded from before it is destroyed, an error
Victor Stinnerdb39a0d2014-01-16 18:58:01 +010083 message is logged. See :ref:`Detect coroutines never scheduled
84 <asyncio-coroutine-not-scheduled>`.
85
Yury Selivanov37f15bc2014-02-20 16:20:44 -050086.. note::
87
88 In this documentation, some methods are documented as coroutines,
89 even if they are plain Python functions returning a :class:`Future`.
90 This is intentional to have a freedom of tweaking the implementation
91 of these functions in the future. If such a function is needed to be
Yury Selivanov04356e12015-06-30 22:13:22 -040092 used in a callback-style code, wrap its result with :func:`ensure_future`.
Yury Selivanov37f15bc2014-02-20 16:20:44 -050093
Victor Stinnerea3183f2013-12-03 01:08:00 +010094
Victor Stinnerb69d62d2013-12-10 02:09:46 +010095.. _asyncio-hello-world-coroutine:
96
Victor Stinner7f314ed2014-10-15 18:49:16 +020097Example: Hello World coroutine
98^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinnerb69d62d2013-12-10 02:09:46 +010099
Victor Stinner7f314ed2014-10-15 18:49:16 +0200100Example of coroutine displaying ``"Hello World"``::
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100101
102 import asyncio
103
Yury Selivanov66f88282015-06-24 11:04:15 -0400104 async def hello_world():
Victor Stinner7f314ed2014-10-15 18:49:16 +0200105 print("Hello World!")
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100106
107 loop = asyncio.get_event_loop()
Victor Stinner7f314ed2014-10-15 18:49:16 +0200108 # Blocking call which returns when the hello_world() coroutine is done
109 loop.run_until_complete(hello_world())
110 loop.close()
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100111
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100112.. seealso::
113
Victor Stinner7f314ed2014-10-15 18:49:16 +0200114 The :ref:`Hello World with call_soon() <asyncio-hello-world-callback>`
Guido van Rossumf68afd82016-08-08 09:41:21 -0700115 example uses the :meth:`AbstractEventLoop.call_soon` method to schedule a
Victor Stinner7f314ed2014-10-15 18:49:16 +0200116 callback.
117
118
119.. _asyncio-date-coroutine:
120
121Example: Coroutine displaying the current date
122^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
123
124Example of coroutine displaying the current date every second during 5 seconds
125using the :meth:`sleep` function::
126
127 import asyncio
128 import datetime
129
Yury Selivanov66f88282015-06-24 11:04:15 -0400130 async def display_date(loop):
131 end_time = loop.time() + 5.0
132 while True:
133 print(datetime.datetime.now())
134 if (loop.time() + 1.0) >= end_time:
135 break
136 await asyncio.sleep(1)
137
138 loop = asyncio.get_event_loop()
139 # Blocking call which returns when the display_date() coroutine is done
140 loop.run_until_complete(display_date(loop))
141 loop.close()
142
Victor Stinner7f314ed2014-10-15 18:49:16 +0200143.. seealso::
144
145 The :ref:`display the current date with call_later()
146 <asyncio-date-callback>` example uses a callback with the
Guido van Rossumf68afd82016-08-08 09:41:21 -0700147 :meth:`AbstractEventLoop.call_later` method.
Victor Stinner7f314ed2014-10-15 18:49:16 +0200148
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100149
150Example: Chain coroutines
151^^^^^^^^^^^^^^^^^^^^^^^^^
152
153Example chaining coroutines::
154
155 import asyncio
156
Yury Selivanov66f88282015-06-24 11:04:15 -0400157 async def compute(x, y):
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100158 print("Compute %s + %s ..." % (x, y))
Yury Selivanov66f88282015-06-24 11:04:15 -0400159 await asyncio.sleep(1.0)
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100160 return x + y
161
Yury Selivanov66f88282015-06-24 11:04:15 -0400162 async def print_sum(x, y):
163 result = await compute(x, y)
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100164 print("%s + %s = %s" % (x, y, result))
165
166 loop = asyncio.get_event_loop()
167 loop.run_until_complete(print_sum(1, 2))
Victor Stinnerf40c6632014-01-28 23:32:40 +0100168 loop.close()
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100169
170``compute()`` is chained to ``print_sum()``: ``print_sum()`` coroutine waits
Brian Curtina1afeec2014-02-08 18:36:14 -0600171until ``compute()`` is completed before returning its result.
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100172
Victor Stinner1c4b8922013-12-12 12:35:17 +0100173Sequence diagram of the example:
174
175.. image:: tulip_coro.png
176 :align: center
177
Guido van Rossumf68afd82016-08-08 09:41:21 -0700178The "Task" is created by the :meth:`AbstractEventLoop.run_until_complete` method
Victor Stinner59759ff2014-01-16 19:30:21 +0100179when it gets a coroutine object instead of a task.
Victor Stinner86e139a2013-12-13 12:51:24 +0100180
181The diagram shows the control flow, it does not describe exactly how things
182work internally. For example, the sleep coroutine creates an internal future
Guido van Rossumf68afd82016-08-08 09:41:21 -0700183which uses :meth:`AbstractEventLoop.call_later` to wake up the task in 1 second.
Victor Stinner1c4b8922013-12-12 12:35:17 +0100184
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100185
Victor Stinner99c2ab42013-12-03 19:17:25 +0100186InvalidStateError
187-----------------
188
189.. exception:: InvalidStateError
190
191 The operation is not allowed in this state.
192
193
Victor Stinner28d0ae482014-05-29 00:04:57 +0200194TimeoutError
195------------
196
197.. exception:: TimeoutError
198
199 The operation exceeded the given deadline.
200
201.. note::
202
203 This exception is different from the builtin :exc:`TimeoutError` exception!
204
205
Victor Stinner99c2ab42013-12-03 19:17:25 +0100206Future
207------
208
209.. class:: Future(\*, loop=None)
210
211 This class is *almost* compatible with :class:`concurrent.futures.Future`.
212
213 Differences:
214
215 - :meth:`result` and :meth:`exception` do not take a timeout argument and
216 raise an exception when the future isn't done yet.
217
218 - Callbacks registered with :meth:`add_done_callback` are always called
Antoine Pitrou22b11282017-11-07 17:03:28 +0100219 via the event loop's :meth:`~AbstractEventLoop.call_soon`.
Victor Stinner99c2ab42013-12-03 19:17:25 +0100220
221 - This class is not compatible with the :func:`~concurrent.futures.wait` and
222 :func:`~concurrent.futures.as_completed` functions in the
223 :mod:`concurrent.futures` package.
224
Victor Stinner83704962015-02-25 14:24:15 +0100225 This class is :ref:`not thread safe <asyncio-multithreading>`.
226
Victor Stinner99c2ab42013-12-03 19:17:25 +0100227 .. method:: cancel()
228
229 Cancel the future and schedule callbacks.
230
231 If the future is already done or cancelled, return ``False``. Otherwise,
232 change the future's state to cancelled, schedule the callbacks and return
233 ``True``.
234
235 .. method:: cancelled()
236
237 Return ``True`` if the future was cancelled.
238
239 .. method:: done()
240
Serhiy Storchaka4adf01c2016-10-19 18:30:05 +0300241 Return ``True`` if the future is done.
Victor Stinner99c2ab42013-12-03 19:17:25 +0100242
243 Done means either that a result / exception are available, or that the
244 future was cancelled.
245
246 .. method:: result()
247
248 Return the result this future represents.
249
250 If the future has been cancelled, raises :exc:`CancelledError`. If the
251 future's result isn't yet available, raises :exc:`InvalidStateError`. If
252 the future is done and has an exception set, this exception is raised.
253
254 .. method:: exception()
255
256 Return the exception that was set on this future.
257
258 The exception (or ``None`` if no exception was set) is returned only if
259 the future is done. If the future has been cancelled, raises
260 :exc:`CancelledError`. If the future isn't done yet, raises
261 :exc:`InvalidStateError`.
262
263 .. method:: add_done_callback(fn)
264
265 Add a callback to be run when the future becomes done.
266
267 The callback is called with a single argument - the future object. If the
268 future is already done when this is called, the callback is scheduled
Guido van Rossumf68afd82016-08-08 09:41:21 -0700269 with :meth:`~AbstractEventLoop.call_soon`.
Victor Stinner99c2ab42013-12-03 19:17:25 +0100270
Victor Stinner8464c242014-11-28 13:15:41 +0100271 :ref:`Use functools.partial to pass parameters to the callback
272 <asyncio-pass-keywords>`. For example,
273 ``fut.add_done_callback(functools.partial(print, "Future:",
274 flush=True))`` will call ``print("Future:", fut, flush=True)``.
275
Victor Stinner99c2ab42013-12-03 19:17:25 +0100276 .. method:: remove_done_callback(fn)
277
278 Remove all instances of a callback from the "call when done" list.
279
280 Returns the number of callbacks removed.
281
282 .. method:: set_result(result)
283
284 Mark the future done and set its result.
285
286 If the future is already done when this method is called, raises
287 :exc:`InvalidStateError`.
288
289 .. method:: set_exception(exception)
290
291 Mark the future done and set an exception.
292
293 If the future is already done when this method is called, raises
294 :exc:`InvalidStateError`.
295
296
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100297Example: Future with run_until_complete()
298^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
299
Victor Stinner59759ff2014-01-16 19:30:21 +0100300Example combining a :class:`Future` and a :ref:`coroutine function
301<coroutine>`::
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100302
303 import asyncio
304
Berker Peksagf5928672017-02-07 11:27:09 +0300305 async def slow_operation(future):
306 await asyncio.sleep(1)
Victor Stinner04e05da2014-02-17 10:54:30 +0100307 future.set_result('Future is done!')
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100308
309 loop = asyncio.get_event_loop()
310 future = asyncio.Future()
Yury Selivanovd7e19bb2015-05-11 16:33:41 -0400311 asyncio.ensure_future(slow_operation(future))
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100312 loop.run_until_complete(future)
313 print(future.result())
Victor Stinnerf40c6632014-01-28 23:32:40 +0100314 loop.close()
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100315
Terry Jan Reedyc935a952014-07-24 02:33:14 -0400316The coroutine function is responsible for the computation (which takes 1 second)
Victor Stinner59759ff2014-01-16 19:30:21 +0100317and it stores the result into the future. The
Guido van Rossumf68afd82016-08-08 09:41:21 -0700318:meth:`~AbstractEventLoop.run_until_complete` method waits for the completion of
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100319the future.
320
321.. note::
Guido van Rossumf68afd82016-08-08 09:41:21 -0700322 The :meth:`~AbstractEventLoop.run_until_complete` method uses internally the
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100323 :meth:`~Future.add_done_callback` method to be notified when the future is
324 done.
325
326
327Example: Future with run_forever()
328^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
329
330The previous example can be written differently using the
331:meth:`Future.add_done_callback` method to describe explicitly the control
332flow::
333
334 import asyncio
335
Berker Peksagf5928672017-02-07 11:27:09 +0300336 async def slow_operation(future):
337 await asyncio.sleep(1)
Victor Stinner04e05da2014-02-17 10:54:30 +0100338 future.set_result('Future is done!')
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100339
340 def got_result(future):
341 print(future.result())
342 loop.stop()
343
344 loop = asyncio.get_event_loop()
345 future = asyncio.Future()
Yury Selivanovd7e19bb2015-05-11 16:33:41 -0400346 asyncio.ensure_future(slow_operation(future))
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100347 future.add_done_callback(got_result)
Victor Stinner04e05da2014-02-17 10:54:30 +0100348 try:
349 loop.run_forever()
350 finally:
351 loop.close()
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100352
Victor Stinner039f7032014-12-02 17:52:45 +0100353In this example, the future is used to link ``slow_operation()`` to
354``got_result()``: when ``slow_operation()`` is done, ``got_result()`` is called
355with the result.
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100356
357
Victor Stinnerea3183f2013-12-03 01:08:00 +0100358Task
359----
360
361.. class:: Task(coro, \*, loop=None)
362
Victor Stinner530ef2f2014-07-08 12:39:10 +0200363 Schedule the execution of a :ref:`coroutine <coroutine>`: wrap it in a
364 future. A task is a subclass of :class:`Future`.
365
R David Murray22dd8332014-09-24 11:09:09 -0400366 A task is responsible for executing a coroutine object in an event loop. If
Victor Stinner530ef2f2014-07-08 12:39:10 +0200367 the wrapped coroutine yields from a future, the task suspends the execution
Berker Peksag002b0a72016-10-04 20:45:47 +0300368 of the wrapped coroutine and waits for the completion of the future. When
Victor Stinner530ef2f2014-07-08 12:39:10 +0200369 the future is done, the execution of the wrapped coroutine restarts with the
370 result or the exception of the future.
371
372 Event loops use cooperative scheduling: an event loop only runs one task at
R David Murray22dd8332014-09-24 11:09:09 -0400373 a time. Other tasks may run in parallel if other event loops are
Victor Stinner530ef2f2014-07-08 12:39:10 +0200374 running in different threads. While a task waits for the completion of a
375 future, the event loop executes a new task.
376
luzpaza5293b42017-11-05 07:37:50 -0600377 The cancellation of a task is different from the cancellation of a
Andrew Svetlovf1240162016-01-11 14:40:35 +0200378 future. Calling :meth:`cancel` will throw a
379 :exc:`~concurrent.futures.CancelledError` to the wrapped
380 coroutine. :meth:`~Future.cancelled` only returns ``True`` if the
Victor Stinner530ef2f2014-07-08 12:39:10 +0200381 wrapped coroutine did not catch the
382 :exc:`~concurrent.futures.CancelledError` exception, or raised a
383 :exc:`~concurrent.futures.CancelledError` exception.
384
385 If a pending task is destroyed, the execution of its wrapped :ref:`coroutine
386 <coroutine>` did not complete. It is probably a bug and a warning is
387 logged: see :ref:`Pending task destroyed <asyncio-pending-task-destroyed>`.
388
Yury Selivanov04356e12015-06-30 22:13:22 -0400389 Don't directly create :class:`Task` instances: use the :func:`ensure_future`
Guido van Rossumf68afd82016-08-08 09:41:21 -0700390 function or the :meth:`AbstractEventLoop.create_task` method.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100391
Victor Stinner83704962015-02-25 14:24:15 +0100392 This class is :ref:`not thread safe <asyncio-multithreading>`.
393
Victor Stinnerea3183f2013-12-03 01:08:00 +0100394 .. classmethod:: all_tasks(loop=None)
395
396 Return a set of all tasks for an event loop.
397
398 By default all tasks for the current event loop are returned.
399
Victor Stinner742520b2013-12-10 12:14:50 +0100400 .. classmethod:: current_task(loop=None)
401
402 Return the currently running task in an event loop or ``None``.
403
404 By default the current task for the current event loop is returned.
405
406 ``None`` is returned when called not in the context of a :class:`Task`.
407
Victor Stinner8d213572014-06-02 23:06:46 +0200408 .. method:: cancel()
409
R David Murray22dd8332014-09-24 11:09:09 -0400410 Request that this task cancel itself.
Victor Stinner8d213572014-06-02 23:06:46 +0200411
412 This arranges for a :exc:`~concurrent.futures.CancelledError` to be
413 thrown into the wrapped coroutine on the next cycle through the event
414 loop. The coroutine then has a chance to clean up or even deny the
415 request using try/except/finally.
416
R David Murray22dd8332014-09-24 11:09:09 -0400417 Unlike :meth:`Future.cancel`, this does not guarantee that the task
Victor Stinner8d213572014-06-02 23:06:46 +0200418 will be cancelled: the exception might be caught and acted upon, delaying
R David Murray22dd8332014-09-24 11:09:09 -0400419 cancellation of the task or preventing cancellation completely. The task
420 may also return a value or raise a different exception.
Victor Stinner8d213572014-06-02 23:06:46 +0200421
422 Immediately after this method is called, :meth:`~Future.cancelled` will
423 not return ``True`` (unless the task was already cancelled). A task will
424 be marked as cancelled when the wrapped coroutine terminates with a
425 :exc:`~concurrent.futures.CancelledError` exception (even if
426 :meth:`cancel` was not called).
427
428 .. method:: get_stack(\*, limit=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100429
430 Return the list of stack frames for this task's coroutine.
431
Andrew Svetlovf1240162016-01-11 14:40:35 +0200432 If the coroutine is not done, this returns the stack where it is
433 suspended. If the coroutine has completed successfully or was
434 cancelled, this returns an empty list. If the coroutine was
435 terminated by an exception, this returns the list of traceback
436 frames.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100437
438 The frames are always ordered from oldest to newest.
439
Brian Curtina1afeec2014-02-08 18:36:14 -0600440 The optional limit gives the maximum number of frames to return; by
Victor Stinnerea3183f2013-12-03 01:08:00 +0100441 default all available frames are returned. Its meaning differs depending
442 on whether a stack or a traceback is returned: the newest frames of a
443 stack are returned, but the oldest frames of a traceback are returned.
444 (This matches the behavior of the traceback module.)
445
446 For reasons beyond our control, only one stack frame is returned for a
447 suspended coroutine.
448
449 .. method:: print_stack(\*, limit=None, file=None)
450
451 Print the stack or traceback for this task's coroutine.
452
453 This produces output similar to that of the traceback module, for the
454 frames retrieved by get_stack(). The limit argument is passed to
455 get_stack(). The file argument is an I/O stream to which the output
R David Murray22dd8332014-09-24 11:09:09 -0400456 is written; by default output is written to sys.stderr.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100457
458
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100459Example: Parallel execution of tasks
460^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
461
462Example executing 3 tasks (A, B, C) in parallel::
463
464 import asyncio
465
Berker Peksagd5adb632017-02-01 22:37:16 +0300466 async def factorial(name, number):
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100467 f = 1
Victor Stinner34f29462013-12-10 02:51:05 +0100468 for i in range(2, number+1):
469 print("Task %s: Compute factorial(%s)..." % (name, i))
Berker Peksagd5adb632017-02-01 22:37:16 +0300470 await asyncio.sleep(1)
Victor Stinner34f29462013-12-10 02:51:05 +0100471 f *= i
472 print("Task %s: factorial(%s) = %s" % (name, number, f))
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100473
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100474 loop = asyncio.get_event_loop()
Berker Peksagd5adb632017-02-01 22:37:16 +0300475 loop.run_until_complete(asyncio.gather(
476 factorial("A", 2),
477 factorial("B", 3),
478 factorial("C", 4),
479 ))
Victor Stinnerf40c6632014-01-28 23:32:40 +0100480 loop.close()
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100481
482Output::
483
Victor Stinner34f29462013-12-10 02:51:05 +0100484 Task A: Compute factorial(2)...
485 Task B: Compute factorial(2)...
486 Task C: Compute factorial(2)...
487 Task A: factorial(2) = 2
488 Task B: Compute factorial(3)...
489 Task C: Compute factorial(3)...
490 Task B: factorial(3) = 6
491 Task C: Compute factorial(4)...
492 Task C: factorial(4) = 24
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100493
Victor Stinner34f29462013-12-10 02:51:05 +0100494A task is automatically scheduled for execution when it is created. The event
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100495loop stops when all tasks are done.
496
497
Victor Stinnerea3183f2013-12-03 01:08:00 +0100498Task functions
499--------------
500
Eli Bendersky029981b2014-01-20 07:02:22 -0800501.. note::
502
Martin Panterc04fb562016-02-10 05:44:01 +0000503 In the functions below, the optional *loop* argument allows explicitly setting
Eli Bendersky029981b2014-01-20 07:02:22 -0800504 the event loop object used by the underlying task or coroutine. If it's
505 not provided, the default event loop is used.
506
Victor Stinner99c2ab42013-12-03 19:17:25 +0100507.. function:: as_completed(fs, \*, loop=None, timeout=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100508
Victor Stinner99c2ab42013-12-03 19:17:25 +0100509 Return an iterator whose values, when waited for, are :class:`Future`
510 instances.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100511
Victor Stinner28d0ae482014-05-29 00:04:57 +0200512 Raises :exc:`asyncio.TimeoutError` if the timeout occurs before all Futures
513 are done.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100514
515 Example::
516
517 for f in as_completed(fs):
518 result = yield from f # The 'yield from' may raise
519 # Use result
520
521 .. note::
522
523 The futures ``f`` are not necessarily members of fs.
524
Yury Selivanovd7e19bb2015-05-11 16:33:41 -0400525.. function:: ensure_future(coro_or_future, \*, loop=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100526
Victor Stinner980dd842014-10-12 21:36:17 +0200527 Schedule the execution of a :ref:`coroutine object <coroutine>`: wrap it in
528 a future. Return a :class:`Task` object.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100529
Victor Stinner99c2ab42013-12-03 19:17:25 +0100530 If the argument is a :class:`Future`, it is returned directly.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100531
Yury Selivanovd7e19bb2015-05-11 16:33:41 -0400532 .. versionadded:: 3.4.4
533
Yury Selivanove319ab02015-12-15 00:45:24 -0500534 .. versionchanged:: 3.5.1
535 The function accepts any :term:`awaitable` object.
536
Victor Stinner337e03f2014-08-11 01:11:13 +0200537 .. seealso::
538
Guido van Rossumf68afd82016-08-08 09:41:21 -0700539 The :meth:`AbstractEventLoop.create_task` method.
Victor Stinner337e03f2014-08-11 01:11:13 +0200540
Yury Selivanovd7e19bb2015-05-11 16:33:41 -0400541.. function:: async(coro_or_future, \*, loop=None)
542
543 A deprecated alias to :func:`ensure_future`.
544
545 .. deprecated:: 3.4.4
546
adisbladis824f6872017-06-09 14:28:59 +0800547.. function:: wrap_future(future, \*, loop=None)
548
549 Wrap a :class:`concurrent.futures.Future` object in a :class:`Future`
550 object.
551
Victor Stinner99c2ab42013-12-03 19:17:25 +0100552.. function:: gather(\*coros_or_futures, loop=None, return_exceptions=False)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100553
Victor Stinner59759ff2014-01-16 19:30:21 +0100554 Return a future aggregating results from the given coroutine objects or
555 futures.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100556
557 All futures must share the same event loop. If all the tasks are done
558 successfully, the returned future's result is the list of results (in the
559 order of the original sequence, not necessarily the order of results
Serhiy Storchaka4adf01c2016-10-19 18:30:05 +0300560 arrival). If *return_exceptions* is true, exceptions in the tasks are
Victor Stinnerea3183f2013-12-03 01:08:00 +0100561 treated the same as successful results, and gathered in the result list;
562 otherwise, the first raised exception will be immediately propagated to the
563 returned future.
564
565 Cancellation: if the outer Future is cancelled, all children (that have not
566 completed yet) are also cancelled. If any child is cancelled, this is
567 treated as if it raised :exc:`~concurrent.futures.CancelledError` -- the
568 outer Future is *not* cancelled in this case. (This is to prevent the
569 cancellation of one child to cause other children to be cancelled.)
570
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100571.. function:: iscoroutine(obj)
572
Yury Selivanov66f88282015-06-24 11:04:15 -0400573 Return ``True`` if *obj* is a :ref:`coroutine object <coroutine>`,
574 which may be based on a generator or an :keyword:`async def` coroutine.
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100575
Yury Selivanov66f88282015-06-24 11:04:15 -0400576.. function:: iscoroutinefunction(func)
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100577
Yury Selivanov66f88282015-06-24 11:04:15 -0400578 Return ``True`` if *func* is determined to be a :ref:`coroutine function
579 <coroutine>`, which may be a decorated generator function or an
580 :keyword:`async def` function.
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100581
Andrew Svetlovf1240162016-01-11 14:40:35 +0200582.. function:: run_coroutine_threadsafe(coro, loop)
583
584 Submit a :ref:`coroutine object <coroutine>` to a given event loop.
585
586 Return a :class:`concurrent.futures.Future` to access the result.
587
588 This function is meant to be called from a different thread than the one
589 where the event loop is running. Usage::
590
591 # Create a coroutine
592 coro = asyncio.sleep(1, result=3)
593 # Submit the coroutine to a given loop
594 future = asyncio.run_coroutine_threadsafe(coro, loop)
595 # Wait for the result with an optional timeout argument
596 assert future.result(timeout) == 3
597
598 If an exception is raised in the coroutine, the returned future will be
599 notified. It can also be used to cancel the task in the event loop::
600
601 try:
602 result = future.result(timeout)
603 except asyncio.TimeoutError:
604 print('The coroutine took too long, cancelling the task...')
605 future.cancel()
606 except Exception as exc:
607 print('The coroutine raised an exception: {!r}'.format(exc))
608 else:
609 print('The coroutine returned: {!r}'.format(result))
610
611 See the :ref:`concurrency and multithreading <asyncio-multithreading>`
612 section of the documentation.
613
614 .. note::
615
Andrew Svetlov3af81f22016-01-11 14:45:25 +0200616 Unlike other functions from the module,
617 :func:`run_coroutine_threadsafe` requires the *loop* argument to
Zachary Waref9aff922016-06-01 00:01:10 -0500618 be passed explicitly.
Andrew Svetlovf1240162016-01-11 14:40:35 +0200619
Andrew Svetlovea471342016-01-11 15:41:43 +0200620 .. versionadded:: 3.5.1
Andrew Svetlovf1240162016-01-11 14:40:35 +0200621
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100622.. coroutinefunction:: sleep(delay, result=None, \*, loop=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100623
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500624 Create a :ref:`coroutine <coroutine>` that completes after a given
Eli Bendersky2d26af82014-01-20 06:59:23 -0800625 time (in seconds). If *result* is provided, it is produced to the caller
626 when the coroutine completes.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100627
Victor Stinner45b27ed2014-02-01 02:36:43 +0100628 The resolution of the sleep depends on the :ref:`granularity of the event
629 loop <asyncio-delayed-calls>`.
630
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100631 This function is a :ref:`coroutine <coroutine>`.
632
Victor Stinnerea3183f2013-12-03 01:08:00 +0100633.. function:: shield(arg, \*, loop=None)
634
635 Wait for a future, shielding it from cancellation.
636
637 The statement::
638
639 res = yield from shield(something())
640
641 is exactly equivalent to the statement::
642
643 res = yield from something()
644
645 *except* that if the coroutine containing it is cancelled, the task running
646 in ``something()`` is not cancelled. From the point of view of
647 ``something()``, the cancellation did not happen. But its caller is still
648 cancelled, so the yield-from expression still raises
649 :exc:`~concurrent.futures.CancelledError`. Note: If ``something()`` is
650 cancelled by other means this will still cancel ``shield()``.
651
652 If you want to completely ignore cancellation (not recommended) you can
653 combine ``shield()`` with a try/except clause, as follows::
654
655 try:
656 res = yield from shield(something())
657 except CancelledError:
658 res = None
659
Yury Selivanov950204d2016-05-16 16:23:00 -0400660
Andrew Svetlovf1240162016-01-11 14:40:35 +0200661.. coroutinefunction:: wait(futures, \*, loop=None, timeout=None,\
662 return_when=ALL_COMPLETED)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100663
Victor Stinner59759ff2014-01-16 19:30:21 +0100664 Wait for the Futures and coroutine objects given by the sequence *futures*
665 to complete. Coroutines will be wrapped in Tasks. Returns two sets of
Victor Stinner99c2ab42013-12-03 19:17:25 +0100666 :class:`Future`: (done, pending).
Victor Stinnerea3183f2013-12-03 01:08:00 +0100667
Victor Stinnerdb74d982014-06-10 11:16:05 +0200668 The sequence *futures* must not be empty.
669
Victor Stinnerea3183f2013-12-03 01:08:00 +0100670 *timeout* can be used to control the maximum number of seconds to wait before
671 returning. *timeout* can be an int or float. If *timeout* is not specified
672 or ``None``, there is no limit to the wait time.
673
674 *return_when* indicates when this function should return. It must be one of
Victor Stinner933a8c82013-12-03 01:59:38 +0100675 the following constants of the :mod:`concurrent.futures` module:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100676
677 .. tabularcolumns:: |l|L|
678
679 +-----------------------------+----------------------------------------+
680 | Constant | Description |
681 +=============================+========================================+
682 | :const:`FIRST_COMPLETED` | The function will return when any |
683 | | future finishes or is cancelled. |
684 +-----------------------------+----------------------------------------+
685 | :const:`FIRST_EXCEPTION` | The function will return when any |
686 | | future finishes by raising an |
687 | | exception. If no future raises an |
688 | | exception then it is equivalent to |
689 | | :const:`ALL_COMPLETED`. |
690 +-----------------------------+----------------------------------------+
691 | :const:`ALL_COMPLETED` | The function will return when all |
692 | | futures finish or are cancelled. |
693 +-----------------------------+----------------------------------------+
694
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500695 This function is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100696
697 Usage::
698
699 done, pending = yield from asyncio.wait(fs)
700
701 .. note::
702
Victor Stinner28d0ae482014-05-29 00:04:57 +0200703 This does not raise :exc:`asyncio.TimeoutError`! Futures that aren't done
704 when the timeout occurs are returned in the second set.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100705
Victor Stinner3e09e322013-12-03 01:22:06 +0100706
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100707.. coroutinefunction:: wait_for(fut, timeout, \*, loop=None)
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100708
709 Wait for the single :class:`Future` or :ref:`coroutine object <coroutine>`
Victor Stinner530ef2f2014-07-08 12:39:10 +0200710 to complete with timeout. If *timeout* is ``None``, block until the future
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100711 completes.
712
Victor Stinner337e03f2014-08-11 01:11:13 +0200713 Coroutine will be wrapped in :class:`Task`.
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100714
715 Returns result of the Future or coroutine. When a timeout occurs, it
Victor Stinner28d0ae482014-05-29 00:04:57 +0200716 cancels the task and raises :exc:`asyncio.TimeoutError`. To avoid the task
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100717 cancellation, wrap it in :func:`shield`.
718
Victor Stinner72dcb0a2015-04-03 17:08:19 +0200719 If the wait is cancelled, the future *fut* is also cancelled.
720
Victor Stinner530ef2f2014-07-08 12:39:10 +0200721 This function is a :ref:`coroutine <coroutine>`, usage::
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500722
Victor Stinner530ef2f2014-07-08 12:39:10 +0200723 result = yield from asyncio.wait_for(fut, 60.0)
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100724
Victor Stinner72dcb0a2015-04-03 17:08:19 +0200725 .. versionchanged:: 3.4.3
726 If the wait is cancelled, the future *fut* is now also cancelled.