blob: e995fb6391adb666e4776f6315449436f69c9ac0 [file] [log] [blame]
R David Murray6a143812013-12-20 14:37:39 -05001.. currentmodule:: asyncio
Victor Stinnerea3183f2013-12-03 01:08:00 +01002
Yury Selivanov3faaa882018-09-14 13:32:07 -07003
4====================
5Coroutines and Tasks
Victor Stinnerea3183f2013-12-03 01:08:00 +01006====================
7
Yury Selivanov3faaa882018-09-14 13:32:07 -07008This section outlines high-level asyncio APIs to work with coroutines
9and Tasks.
lf627d2c82017-07-25 17:03:51 -060010
Yury Selivanov3faaa882018-09-14 13:32:07 -070011.. contents::
12 :depth: 1
13 :local:
14
lf627d2c82017-07-25 17:03:51 -060015
Victor Stinnerea3183f2013-12-03 01:08:00 +010016.. _coroutine:
17
18Coroutines
Yury Selivanov3faaa882018-09-14 13:32:07 -070019==========
Victor Stinnerea3183f2013-12-03 01:08:00 +010020
Yury Selivanov3faaa882018-09-14 13:32:07 -070021Coroutines declared with async/await syntax is the preferred way of
22writing asyncio applications. For example, the following snippet
Yury Selivanovb042cf12018-09-18 02:47:54 -040023of code (requires Python 3.7+) prints "hello", waits 1 second,
24and then prints "world"::
Victor Stinnerea3183f2013-12-03 01:08:00 +010025
Yury Selivanov3faaa882018-09-14 13:32:07 -070026 >>> import asyncio
Victor Stinnerea3183f2013-12-03 01:08:00 +010027
Yury Selivanov3faaa882018-09-14 13:32:07 -070028 >>> async def main():
29 ... print('hello')
30 ... await asyncio.sleep(1)
31 ... print('world')
Victor Stinnerea3183f2013-12-03 01:08:00 +010032
Yury Selivanov3faaa882018-09-14 13:32:07 -070033 >>> asyncio.run(main())
34 hello
35 world
Victor Stinnerea3183f2013-12-03 01:08:00 +010036
Yury Selivanov3faaa882018-09-14 13:32:07 -070037Note that simply calling a coroutine will not schedule it to
38be executed::
Victor Stinnerea3183f2013-12-03 01:08:00 +010039
Yury Selivanov3faaa882018-09-14 13:32:07 -070040 >>> main()
41 <coroutine object main at 0x1053bb7c8>
Victor Stinnerea3183f2013-12-03 01:08:00 +010042
Yury Selivanov3faaa882018-09-14 13:32:07 -070043To actually run a coroutine asyncio provides three main mechanisms:
Victor Stinnerea3183f2013-12-03 01:08:00 +010044
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -040045* The :func:`asyncio.run` function to run the top-level
Yury Selivanov3faaa882018-09-14 13:32:07 -070046 entry point "main()" function (see the above example.)
Victor Stinnerea3183f2013-12-03 01:08:00 +010047
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -040048* Awaiting on a coroutine. The following snippet of code will
Yury Selivanov3faaa882018-09-14 13:32:07 -070049 print "hello" after waiting for 1 second, and then print "world"
50 after waiting for *another* 2 seconds::
Victor Stinnerea3183f2013-12-03 01:08:00 +010051
Yury Selivanov3faaa882018-09-14 13:32:07 -070052 import asyncio
53 import time
Victor Stinnerea3183f2013-12-03 01:08:00 +010054
Yury Selivanov3faaa882018-09-14 13:32:07 -070055 async def say_after(delay, what):
56 await asyncio.sleep(delay)
57 print(what)
58
59 async def main():
60 print('started at', time.strftime('%X'))
61
62 await say_after(1, 'hello')
63 await say_after(2, 'world')
64
65 print('finished at', time.strftime('%X'))
66
67 asyncio.run(main())
68
69 Expected output::
70
71 started at 17:13:52
72 hello
73 world
74 finished at 17:13:55
75
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -040076* The :func:`asyncio.create_task` function to run coroutines
Yury Selivanov3faaa882018-09-14 13:32:07 -070077 concurrently as asyncio :class:`Tasks <Task>`.
78
Danny Hermes7bfbda42018-09-17 21:49:21 -070079 Let's modify the above example and run two ``say_after`` coroutines
Yury Selivanov3faaa882018-09-14 13:32:07 -070080 *concurrently*::
81
82 async def main():
83 task1 = asyncio.create_task(
84 say_after(1, 'hello'))
85
86 task2 = asyncio.create_task(
87 say_after(2, 'world'))
88
89 print('started at', time.strftime('%X'))
90
91 # Wait until both tasks are completed (should take
92 # around 2 seconds.)
93 await task1
94 await task2
95
96 print('finished at', time.strftime('%X'))
97
98 Note that expected output now shows that the snippet runs
99 1 second faster than before::
100
101 started at 17:14:32
102 hello
103 world
104 finished at 17:14:34
105
Yury Selivanov47150392018-09-18 17:55:44 -0400106
107.. _asyncio-awaitables:
108
109Awaitables
110==========
111
Yury Selivanove247b462018-09-20 12:43:59 -0400112We say that an object is an **awaitable** object if it can be used
113in an :keyword:`await` expression. Many asyncio APIs are designed to
114accept awaitables.
115
116There are three main types of *awaitable* objects:
117**coroutines**, **Tasks**, and **Futures**.
Yury Selivanov47150392018-09-18 17:55:44 -0400118
119
Yury Selivanove247b462018-09-20 12:43:59 -0400120.. rubric:: Coroutines
Yury Selivanov47150392018-09-18 17:55:44 -0400121
Yury Selivanove247b462018-09-20 12:43:59 -0400122Python coroutines are *awaitables* and therefore can be awaited from
123other coroutines::
124
125 import asyncio
Yury Selivanov47150392018-09-18 17:55:44 -0400126
127 async def nested():
128 return 42
129
130 async def main():
Yury Selivanove247b462018-09-20 12:43:59 -0400131 # Nothing happens if we just call "nested()".
Yury Selivanovdb1a80e2018-09-21 16:23:15 -0400132 # A coroutine object is created but not awaited,
133 # so it *won't run at all*.
Yury Selivanove247b462018-09-20 12:43:59 -0400134 nested()
135
136 # Let's do it differently now and await it:
137 print(await nested()) # will print "42".
138
139 asyncio.run(main())
140
141.. important::
142
143 In this documentation the term "coroutine" can be used for
144 two closely related concepts:
145
146 * a *coroutine function*: an :keyword:`async def` function;
147
148 * a *coroutine object*: an object returned by calling a
149 *coroutine function*.
150
151asyncio also supports legacy :ref:`generator-based
152<asyncio_generator_based_coro>` coroutines.
153
154
155.. rubric:: Tasks
Yury Selivanov47150392018-09-18 17:55:44 -0400156
157*Tasks* are used to schedule coroutines *concurrently*.
Yury Selivanov47150392018-09-18 17:55:44 -0400158
Yury Selivanove247b462018-09-20 12:43:59 -0400159When a coroutine is wrapped into a *Task* with functions like
160:func:`asyncio.create_task` the coroutine is automatically
161scheduled to run soon::
Yury Selivanov3faaa882018-09-14 13:32:07 -0700162
Yury Selivanove247b462018-09-20 12:43:59 -0400163 import asyncio
Yury Selivanov3faaa882018-09-14 13:32:07 -0700164
Yury Selivanove247b462018-09-20 12:43:59 -0400165 async def nested():
166 return 42
167
168 async def main():
169 # Schedule nested() to run soon concurrently
170 # with "main()".
171 task = asyncio.create_task(nested())
172
173 # "task" can now be used to cancel "nested()", or
174 # can simply be awaited to wait until it is complete:
175 await task
176
177 asyncio.run(main())
Victor Stinner337e03f2014-08-11 01:11:13 +0200178
Victor Stinnerea3183f2013-12-03 01:08:00 +0100179
Yury Selivanov47150392018-09-18 17:55:44 -0400180.. rubric:: Futures
181
Yury Selivanove247b462018-09-20 12:43:59 -0400182A :class:`Future` is a special **low-level** awaitable object that
183represents an **eventual result** of an asynchronous operation.
Yury Selivanov47150392018-09-18 17:55:44 -0400184
Yury Selivanove247b462018-09-20 12:43:59 -0400185When a Future object is *awaited* it means that the coroutine will
186wait until the Future is resolved in some other place.
187
Yury Selivanov47150392018-09-18 17:55:44 -0400188Future objects in asyncio are needed to allow callback-based code
189to be used with async/await.
190
Yury Selivanove247b462018-09-20 12:43:59 -0400191Normally **there is no need** to create Future objects at the
Yury Selivanov47150392018-09-18 17:55:44 -0400192application level code.
193
194Future objects, sometimes exposed by libraries and some asyncio
Yury Selivanove247b462018-09-20 12:43:59 -0400195APIs, can be awaited::
Yury Selivanov47150392018-09-18 17:55:44 -0400196
197 async def main():
198 await function_that_returns_a_future_object()
199
200 # this is also valid:
201 await asyncio.gather(
202 function_that_returns_a_future_object(),
203 some_python_coroutine()
204 )
205
Yury Selivanove247b462018-09-20 12:43:59 -0400206A good example of a low-level function that returns a Future object
207is :meth:`loop.run_in_executor`.
208
Yury Selivanov47150392018-09-18 17:55:44 -0400209
Yury Selivanov3faaa882018-09-14 13:32:07 -0700210Running an asyncio Program
211==========================
Victor Stinnerea3183f2013-12-03 01:08:00 +0100212
Elvis Pranskevichus63536bd2018-05-19 23:15:06 -0400213.. function:: run(coro, \*, debug=False)
Yury Selivanov02a0a192017-12-14 09:42:21 -0500214
215 This function runs the passed coroutine, taking care of
Yury Selivanov47150392018-09-18 17:55:44 -0400216 managing the asyncio event loop and *finalizing asynchronous
217 generators*.
Yury Selivanov02a0a192017-12-14 09:42:21 -0500218
219 This function cannot be called when another asyncio event loop is
220 running in the same thread.
221
Yury Selivanov3faaa882018-09-14 13:32:07 -0700222 If *debug* is ``True``, the event loop will be run in debug mode.
Yury Selivanov02a0a192017-12-14 09:42:21 -0500223
224 This function always creates a new event loop and closes it at
225 the end. It should be used as a main entry point for asyncio
226 programs, and should ideally only be called once.
227
228 .. versionadded:: 3.7
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400229 **Important:** this function has been added to asyncio in
230 Python 3.7 on a :term:`provisional basis <provisional api>`.
Yury Selivanov02a0a192017-12-14 09:42:21 -0500231
232
Yury Selivanov3faaa882018-09-14 13:32:07 -0700233Creating Tasks
234==============
Victor Stinnerea3183f2013-12-03 01:08:00 +0100235
Alex Grönholmcca4eec2018-08-09 00:06:47 +0300236.. function:: create_task(coro, \*, name=None)
Andrew Svetlovf74ef452017-12-15 07:04:38 +0200237
Yury Selivanove247b462018-09-20 12:43:59 -0400238 Wrap the *coro* :ref:`coroutine <coroutine>` into a :class:`Task`
239 and schedule its execution. Return the Task object.
Alex Grönholmcca4eec2018-08-09 00:06:47 +0300240
241 If *name* is not ``None``, it is set as the name of the task using
242 :meth:`Task.set_name`.
Andrew Svetlovf74ef452017-12-15 07:04:38 +0200243
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400244 The task is executed in the loop returned by :func:`get_running_loop`,
Andrew Svetlovf74ef452017-12-15 07:04:38 +0200245 :exc:`RuntimeError` is raised if there is no running loop in
246 current thread.
247
Yury Selivanov47150392018-09-18 17:55:44 -0400248 This function has been **added in Python 3.7**. Prior to
249 Python 3.7, the low-level :func:`asyncio.ensure_future` function
250 can be used instead::
251
252 async def coro():
253 ...
254
255 # In Python 3.7+
256 task = asyncio.create_task(coro())
257 ...
258
259 # This works in all Python versions but is less readable
260 task = asyncio.ensure_future(coro())
261 ...
262
Andrew Svetlovf74ef452017-12-15 07:04:38 +0200263 .. versionadded:: 3.7
264
Alex Grönholmcca4eec2018-08-09 00:06:47 +0300265 .. versionchanged:: 3.8
266 Added the ``name`` parameter.
267
Victor Stinnerea3183f2013-12-03 01:08:00 +0100268
Yury Selivanov3faaa882018-09-14 13:32:07 -0700269Sleeping
270========
Andrew Svetlovf1240162016-01-11 14:40:35 +0200271
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100272.. coroutinefunction:: sleep(delay, result=None, \*, loop=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100273
Yury Selivanov3faaa882018-09-14 13:32:07 -0700274 Block for *delay* seconds.
275
276 If *result* is provided, it is returned to the caller
Eli Bendersky2d26af82014-01-20 06:59:23 -0800277 when the coroutine completes.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100278
Yury Selivanov47150392018-09-18 17:55:44 -0400279 The *loop* argument is deprecated and scheduled for removal
280 in Python 4.0.
281
Yury Selivanov7372c3b2018-09-14 15:11:24 -0700282 .. _asyncio_example_sleep:
Victor Stinner45b27ed2014-02-01 02:36:43 +0100283
Yury Selivanov3faaa882018-09-14 13:32:07 -0700284 Example of coroutine displaying the current date every second
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400285 for 5 seconds::
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100286
Yury Selivanov3faaa882018-09-14 13:32:07 -0700287 import asyncio
288 import datetime
Victor Stinnerea3183f2013-12-03 01:08:00 +0100289
Yury Selivanov3faaa882018-09-14 13:32:07 -0700290 async def display_date():
291 loop = asyncio.get_running_loop()
292 end_time = loop.time() + 5.0
293 while True:
294 print(datetime.datetime.now())
295 if (loop.time() + 1.0) >= end_time:
296 break
297 await asyncio.sleep(1)
298
299 asyncio.run(display_date())
300
301
302Running Tasks Concurrently
303==========================
304
Yury Selivanove247b462018-09-20 12:43:59 -0400305.. awaitablefunction:: gather(\*aws, loop=None, return_exceptions=False)
Yury Selivanov3faaa882018-09-14 13:32:07 -0700306
Yury Selivanove247b462018-09-20 12:43:59 -0400307 Run :ref:`awaitable objects <asyncio-awaitables>` in the *aws*
Yury Selivanov47150392018-09-18 17:55:44 -0400308 sequence *concurrently*.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700309
Yury Selivanove247b462018-09-20 12:43:59 -0400310 If any awaitable in *aws* is a coroutine, it is automatically
Yury Selivanov47150392018-09-18 17:55:44 -0400311 scheduled as a Task.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700312
Yury Selivanov47150392018-09-18 17:55:44 -0400313 If all awaitables are completed successfully, the result is an
314 aggregate list of returned values. The order of result values
Yury Selivanove247b462018-09-20 12:43:59 -0400315 corresponds to the order of awaitables in *aws*.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700316
Yury Selivanovdb1a80e2018-09-21 16:23:15 -0400317 If *return_exceptions* is ``False`` (default), the first
318 raised exception is immediately propagated to the task that
319 awaits on ``gather()``. Other awaitables in the *aws* sequence
320 **won't be cancelled** and will continue to run.
321
Yury Selivanov47150392018-09-18 17:55:44 -0400322 If *return_exceptions* is ``True``, exceptions are treated the
323 same as successful results, and aggregated in the result list.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700324
Yury Selivanovdb1a80e2018-09-21 16:23:15 -0400325 If ``gather()`` is *cancelled*, all submitted awaitables
Yury Selivanov3faaa882018-09-14 13:32:07 -0700326 (that have not completed yet) are also *cancelled*.
327
Yury Selivanove247b462018-09-20 12:43:59 -0400328 If any Task or Future from the *aws* sequence is *cancelled*, it is
Yury Selivanov47150392018-09-18 17:55:44 -0400329 treated as if it raised :exc:`CancelledError` -- the ``gather()``
330 call is **not** cancelled in this case. This is to prevent the
331 cancellation of one submitted Task/Future to cause other
332 Tasks/Futures to be cancelled.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700333
Yury Selivanov7372c3b2018-09-14 15:11:24 -0700334 .. _asyncio_example_gather:
335
Yury Selivanov3faaa882018-09-14 13:32:07 -0700336 Example::
337
338 import asyncio
339
340 async def factorial(name, number):
341 f = 1
342 for i in range(2, number + 1):
343 print(f"Task {name}: Compute factorial({i})...")
344 await asyncio.sleep(1)
345 f *= i
346 print(f"Task {name}: factorial({number}) = {f}")
347
348 async def main():
Yury Selivanov47150392018-09-18 17:55:44 -0400349 # Schedule three calls *concurrently*:
Yury Selivanov3faaa882018-09-14 13:32:07 -0700350 await asyncio.gather(
351 factorial("A", 2),
352 factorial("B", 3),
353 factorial("C", 4),
Miguel Ángel García9c53fa62018-09-18 08:01:26 +0200354 )
Yury Selivanov3faaa882018-09-14 13:32:07 -0700355
356 asyncio.run(main())
357
358 # Expected output:
359 #
360 # Task A: Compute factorial(2)...
361 # Task B: Compute factorial(2)...
362 # Task C: Compute factorial(2)...
363 # Task A: factorial(2) = 2
364 # Task B: Compute factorial(3)...
365 # Task C: Compute factorial(3)...
366 # Task B: factorial(3) = 6
367 # Task C: Compute factorial(4)...
368 # Task C: factorial(4) = 24
369
Yury Selivanov47150392018-09-18 17:55:44 -0400370 .. versionchanged:: 3.7
371 If the *gather* itself is cancelled, the cancellation is
372 propagated regardless of *return_exceptions*.
373
Yury Selivanov3faaa882018-09-14 13:32:07 -0700374
Yury Selivanovdb1a80e2018-09-21 16:23:15 -0400375Shielding From Cancellation
376===========================
Yury Selivanov3faaa882018-09-14 13:32:07 -0700377
Yury Selivanove247b462018-09-20 12:43:59 -0400378.. awaitablefunction:: shield(aw, \*, loop=None)
Yury Selivanov3faaa882018-09-14 13:32:07 -0700379
Yury Selivanov47150392018-09-18 17:55:44 -0400380 Protect an :ref:`awaitable object <asyncio-awaitables>`
381 from being :meth:`cancelled <Task.cancel>`.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700382
Yury Selivanovdb1a80e2018-09-21 16:23:15 -0400383 If *aw* is a coroutine it is automatically scheduled as a Task.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100384
385 The statement::
386
Andrew Svetlov88743422017-12-11 17:35:49 +0200387 res = await shield(something())
Victor Stinnerea3183f2013-12-03 01:08:00 +0100388
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400389 is equivalent to::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100390
Andrew Svetlov88743422017-12-11 17:35:49 +0200391 res = await something()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100392
Yury Selivanov3faaa882018-09-14 13:32:07 -0700393 *except* that if the coroutine containing it is cancelled, the
394 Task running in ``something()`` is not cancelled. From the point
395 of view of ``something()``, the cancellation did not happen.
396 Although its caller is still cancelled, so the "await" expression
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400397 still raises a :exc:`CancelledError`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100398
Yury Selivanov3faaa882018-09-14 13:32:07 -0700399 If ``something()`` is cancelled by other means (i.e. from within
400 itself) that would also cancel ``shield()``.
401
402 If it is desired to completely ignore cancellation (not recommended)
403 the ``shield()`` function should be combined with a try/except
404 clause, as follows::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100405
406 try:
Andrew Svetlov88743422017-12-11 17:35:49 +0200407 res = await shield(something())
Victor Stinnerea3183f2013-12-03 01:08:00 +0100408 except CancelledError:
409 res = None
410
Yury Selivanov950204d2016-05-16 16:23:00 -0400411
Yury Selivanov3faaa882018-09-14 13:32:07 -0700412Timeouts
413========
414
Yury Selivanove247b462018-09-20 12:43:59 -0400415.. coroutinefunction:: wait_for(aw, timeout, \*, loop=None)
Yury Selivanov3faaa882018-09-14 13:32:07 -0700416
Yury Selivanove247b462018-09-20 12:43:59 -0400417 Wait for the *aw* :ref:`awaitable <asyncio-awaitables>`
Yury Selivanov47150392018-09-18 17:55:44 -0400418 to complete with a timeout.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700419
Yury Selivanove247b462018-09-20 12:43:59 -0400420 If *aw* is a coroutine it is automatically scheduled as a Task.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700421
422 *timeout* can either be ``None`` or a float or int number of seconds
423 to wait for. If *timeout* is ``None``, block until the future
424 completes.
425
426 If a timeout occurs, it cancels the task and raises
427 :exc:`asyncio.TimeoutError`.
428
Yury Selivanov47150392018-09-18 17:55:44 -0400429 To avoid the task :meth:`cancellation <Task.cancel>`,
430 wrap it in :func:`shield`.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700431
432 The function will wait until the future is actually cancelled,
433 so the total wait time may exceed the *timeout*.
434
Yury Selivanove247b462018-09-20 12:43:59 -0400435 If the wait is cancelled, the future *aw* is also cancelled.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700436
Yury Selivanov47150392018-09-18 17:55:44 -0400437 The *loop* argument is deprecated and scheduled for removal
438 in Python 4.0.
439
Yury Selivanov7372c3b2018-09-14 15:11:24 -0700440 .. _asyncio_example_waitfor:
441
Yury Selivanov3faaa882018-09-14 13:32:07 -0700442 Example::
443
444 async def eternity():
445 # Sleep for one hour
446 await asyncio.sleep(3600)
447 print('yay!')
448
449 async def main():
450 # Wait for at most 1 second
451 try:
452 await asyncio.wait_for(eternity(), timeout=1.0)
453 except asyncio.TimeoutError:
454 print('timeout!')
455
456 asyncio.run(main())
457
458 # Expected output:
459 #
460 # timeout!
461
462 .. versionchanged:: 3.7
Yury Selivanove247b462018-09-20 12:43:59 -0400463 When *aw* is cancelled due to a timeout, ``wait_for`` waits
464 for *aw* to be cancelled. Previously, it raised
Yury Selivanov3faaa882018-09-14 13:32:07 -0700465 :exc:`asyncio.TimeoutError` immediately.
466
467
468Waiting Primitives
469==================
470
Yury Selivanove247b462018-09-20 12:43:59 -0400471.. coroutinefunction:: wait(aws, \*, loop=None, timeout=None,\
Andrew Svetlovf1240162016-01-11 14:40:35 +0200472 return_when=ALL_COMPLETED)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100473
Yury Selivanove247b462018-09-20 12:43:59 -0400474 Run :ref:`awaitable objects <asyncio-awaitables>` in the *aws*
Yury Selivanov47150392018-09-18 17:55:44 -0400475 sequence concurrently and block until the condition specified
476 by *return_when*.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100477
Yury Selivanove247b462018-09-20 12:43:59 -0400478 If any awaitable in *aws* is a coroutine, it is automatically
Yury Selivanov47150392018-09-18 17:55:44 -0400479 scheduled as a Task.
Victor Stinnerdb74d982014-06-10 11:16:05 +0200480
Yury Selivanov3faaa882018-09-14 13:32:07 -0700481 Returns two sets of Tasks/Futures: ``(done, pending)``.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100482
Yury Selivanov47150392018-09-18 17:55:44 -0400483 The *loop* argument is deprecated and scheduled for removal
484 in Python 4.0.
485
Yury Selivanov3faaa882018-09-14 13:32:07 -0700486 *timeout* (a float or int), if specified, can be used to control
487 the maximum number of seconds to wait before returning.
488
489 Note that this function does not raise :exc:`asyncio.TimeoutError`.
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400490 Futures or Tasks that aren't done when the timeout occurs are simply
Yury Selivanov3faaa882018-09-14 13:32:07 -0700491 returned in the second set.
492
493 *return_when* indicates when this function should return. It must
494 be one of the following constants:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100495
496 .. tabularcolumns:: |l|L|
497
498 +-----------------------------+----------------------------------------+
499 | Constant | Description |
500 +=============================+========================================+
501 | :const:`FIRST_COMPLETED` | The function will return when any |
502 | | future finishes or is cancelled. |
503 +-----------------------------+----------------------------------------+
504 | :const:`FIRST_EXCEPTION` | The function will return when any |
505 | | future finishes by raising an |
506 | | exception. If no future raises an |
507 | | exception then it is equivalent to |
508 | | :const:`ALL_COMPLETED`. |
509 +-----------------------------+----------------------------------------+
510 | :const:`ALL_COMPLETED` | The function will return when all |
511 | | futures finish or are cancelled. |
512 +-----------------------------+----------------------------------------+
513
Yury Selivanov3faaa882018-09-14 13:32:07 -0700514 Unlike :func:`~asyncio.wait_for`, ``wait()`` does not cancel the
515 futures when a timeout occurs.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100516
517 Usage::
518
Yury Selivanove247b462018-09-20 12:43:59 -0400519 done, pending = await asyncio.wait(aws)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100520
Victor Stinnerea3183f2013-12-03 01:08:00 +0100521
Yury Selivanove247b462018-09-20 12:43:59 -0400522.. function:: as_completed(aws, \*, loop=None, timeout=None)
Yury Selivanov3faaa882018-09-14 13:32:07 -0700523
Yury Selivanove247b462018-09-20 12:43:59 -0400524 Run :ref:`awaitable objects <asyncio-awaitables>` in the *aws*
Yury Selivanov47150392018-09-18 17:55:44 -0400525 set concurrently. Return an iterator of :class:`Future` objects.
526 Each Future object returned represents the earliest result
527 from the set of the remaining awaitables.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700528
529 Raises :exc:`asyncio.TimeoutError` if the timeout occurs before
530 all Futures are done.
531
532 Example::
533
Yury Selivanove247b462018-09-20 12:43:59 -0400534 for f in as_completed(aws):
Yury Selivanov47150392018-09-18 17:55:44 -0400535 earliest_result = await f
Yury Selivanov3faaa882018-09-14 13:32:07 -0700536 # ...
Victor Stinnerea3183f2013-12-03 01:08:00 +0100537
Victor Stinner3e09e322013-12-03 01:22:06 +0100538
Yury Selivanov3faaa882018-09-14 13:32:07 -0700539Scheduling From Other Threads
540=============================
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100541
Yury Selivanov3faaa882018-09-14 13:32:07 -0700542.. function:: run_coroutine_threadsafe(coro, loop)
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100543
Yury Selivanov3faaa882018-09-14 13:32:07 -0700544 Submit a coroutine to the given event loop. Thread-safe.
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100545
Yury Selivanov47150392018-09-18 17:55:44 -0400546 Return a :class:`concurrent.futures.Future` to wait for the result
547 from another OS thread.
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100548
Yury Selivanov3faaa882018-09-14 13:32:07 -0700549 This function is meant to be called from a different OS thread
550 than the one where the event loop is running. Example::
Victor Stinner72dcb0a2015-04-03 17:08:19 +0200551
Yury Selivanov3faaa882018-09-14 13:32:07 -0700552 # Create a coroutine
553 coro = asyncio.sleep(1, result=3)
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500554
Yury Selivanov3faaa882018-09-14 13:32:07 -0700555 # Submit the coroutine to a given loop
556 future = asyncio.run_coroutine_threadsafe(coro, loop)
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100557
Yury Selivanov3faaa882018-09-14 13:32:07 -0700558 # Wait for the result with an optional timeout argument
559 assert future.result(timeout) == 3
560
561 If an exception is raised in the coroutine, the returned Future
562 will be notified. It can also be used to cancel the task in
563 the event loop::
564
565 try:
566 result = future.result(timeout)
567 except asyncio.TimeoutError:
568 print('The coroutine took too long, cancelling the task...')
569 future.cancel()
570 except Exception as exc:
571 print('The coroutine raised an exception: {!r}'.format(exc))
572 else:
573 print('The coroutine returned: {!r}'.format(result))
574
575 See the :ref:`concurrency and multithreading <asyncio-multithreading>`
576 section of the documentation.
577
578 Unlike other asyncio functions this functions requires the *loop*
579 argument to be passed explicitly.
580
581 .. versionadded:: 3.5.1
582
583
584Introspection
585=============
586
587
588.. function:: current_task(loop=None)
589
590 Return the currently running :class:`Task` instance, or ``None`` if
591 no task is running.
592
593 If *loop* is ``None`` :func:`get_running_loop` is used to get
594 the current loop.
595
596 .. versionadded:: 3.7
597
598
599.. function:: all_tasks(loop=None)
600
601 Return a set of not yet finished :class:`Task` objects run by
602 the loop.
603
604 If *loop* is ``None``, :func:`get_running_loop` is used for getting
605 current loop.
606
607 .. versionadded:: 3.7
608
609
610Task Object
611===========
612
613.. class:: Task(coro, \*, loop=None, name=None)
614
Yury Selivanovdb1a80e2018-09-21 16:23:15 -0400615 A :class:`Future-like <Future>` object that runs a Python
Yury Selivanov3faaa882018-09-14 13:32:07 -0700616 :ref:`coroutine <coroutine>`. Not thread-safe.
617
618 Tasks are used to run coroutines in event loops.
619 If a coroutine awaits on a Future, the Task suspends
620 the execution of the coroutine and waits for the completion
621 of the Future. When the Future is *done*, the execution of
622 the wrapped coroutine resumes.
623
624 Event loops use cooperative scheduling: an event loop runs
625 one Task at a time. While a Task awaits for the completion of a
626 Future, the event loop runs other Tasks, callbacks, or performs
627 IO operations.
628
629 Use the high-level :func:`asyncio.create_task` function to create
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400630 Tasks, or the low-level :meth:`loop.create_task` or
631 :func:`ensure_future` functions. Manual instantiation of Tasks
632 is discouraged.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700633
634 To cancel a running Task use the :meth:`cancel` method. Calling it
635 will cause the Task to throw a :exc:`CancelledError` exception into
636 the wrapped coroutine. If a coroutine is awaiting on a Future
637 object during cancellation, the Future object will be cancelled.
638
639 :meth:`cancelled` can be used to check if the Task was cancelled.
640 The method returns ``True`` if the wrapped coroutine did not
641 suppress the :exc:`CancelledError` exception and was actually
642 cancelled.
643
644 :class:`asyncio.Task` inherits from :class:`Future` all of its
645 APIs except :meth:`Future.set_result` and
646 :meth:`Future.set_exception`.
647
648 Tasks support the :mod:`contextvars` module. When a Task
649 is created it copies the current context and later runs its
650 coroutine in the copied context.
Elvis Pranskevichuse2b340a2018-05-29 17:31:01 -0400651
652 .. versionchanged:: 3.7
Yury Selivanov3faaa882018-09-14 13:32:07 -0700653 Added support for the :mod:`contextvars` module.
654
655 .. versionchanged:: 3.8
656 Added the ``name`` parameter.
657
658 .. method:: cancel()
659
660 Request the Task to be cancelled.
661
662 This arranges for a :exc:`CancelledError` exception to be thrown
663 into the wrapped coroutine on the next cycle of the event loop.
664
665 The coroutine then has a chance to clean up or even deny the
666 request by suppressing the exception with a :keyword:`try` ...
667 ... ``except CancelledError`` ... :keyword:`finally` block.
668 Therefore, unlike :meth:`Future.cancel`, :meth:`Task.cancel` does
669 not guarantee that the Task will be cancelled, although
670 suppressing cancellation completely is not common and is actively
671 discouraged.
672
Yury Selivanov7372c3b2018-09-14 15:11:24 -0700673 .. _asyncio_example_task_cancel:
674
Yury Selivanov3faaa882018-09-14 13:32:07 -0700675 The following example illustrates how coroutines can intercept
676 the cancellation request::
677
678 async def cancel_me():
679 print('cancel_me(): before sleep')
680
681 try:
682 # Wait for 1 hour
683 await asyncio.sleep(3600)
684 except asyncio.CancelledError:
685 print('cancel_me(): cancel sleep')
686 raise
687 finally:
688 print('cancel_me(): after sleep')
689
690 async def main():
691 # Create a "cancel_me" Task
692 task = asyncio.create_task(cancel_me())
693
694 # Wait for 1 second
695 await asyncio.sleep(1)
696
697 task.cancel()
698 try:
699 await task
700 except asyncio.CancelledError:
701 print("main(): cancel_me is cancelled now")
702
703 asyncio.run(main())
704
705 # Expected output:
706 #
707 # cancel_me(): before sleep
708 # cancel_me(): cancel sleep
709 # cancel_me(): after sleep
710 # main(): cancel_me is cancelled now
711
712 .. method:: cancelled()
713
714 Return ``True`` if the Task is *cancelled*.
715
716 The Task is *cancelled* when the cancellation was requested with
717 :meth:`cancel` and the wrapped coroutine propagated the
718 :exc:`CancelledError` exception thrown into it.
719
720 .. method:: done()
721
722 Return ``True`` if the Task is *done*.
723
724 A Task is *done* when the wrapped coroutine either returned
725 a value, raised an exception, or the Task was cancelled.
726
Yury Selivanove247b462018-09-20 12:43:59 -0400727 .. method:: result()
728
729 Return the result of the Task.
730
731 If the Task is *done*, the result of the wrapped coroutine
732 is returned (or if the coroutine raised an exception, that
733 exception is re-raised.)
734
735 If the Task has been *cancelled*, this method raises
736 a :exc:`CancelledError` exception.
737
738 If the Task's result isn't yet available, this method raises
739 a :exc:`InvalidStateError` exception.
740
741 .. method:: exception()
742
743 Return the exception of the Task.
744
745 If the wrapped coroutine raised an exception that exception
746 is returned. If the wrapped coroutine returned normally
747 this method returns ``None``.
748
749 If the Task has been *cancelled*, this method raises a
750 :exc:`CancelledError` exception.
751
752 If the Task isn't *done* yet, this method raises an
753 :exc:`InvalidStateError` exception.
754
755 .. method:: add_done_callback(callback, *, context=None)
756
757 Add a callback to be run when the Task is *done*.
758
759 This method should only be used in low-level callback-based code.
760
761 See the documentation of :meth:`Future.add_done_callback`
762 for more details.
763
764 .. method:: remove_done_callback(callback)
765
766 Remove *callback* from the callbacks list.
767
768 This method should only be used in low-level callback-based code.
769
770 See the documentation of :meth:`Future.remove_done_callback`
771 for more details.
772
Yury Selivanov3faaa882018-09-14 13:32:07 -0700773 .. method:: get_stack(\*, limit=None)
774
775 Return the list of stack frames for this Task.
776
777 If the wrapped coroutine is not done, this returns the stack
778 where it is suspended. If the coroutine has completed
779 successfully or was cancelled, this returns an empty list.
780 If the coroutine was terminated by an exception, this returns
781 the list of traceback frames.
782
783 The frames are always ordered from oldest to newest.
784
785 Only one stack frame is returned for a suspended coroutine.
786
787 The optional *limit* argument sets the maximum number of frames
788 to return; by default all available frames are returned.
789 The ordering of the returned list differs depending on whether
790 a stack or a traceback is returned: the newest frames of a
791 stack are returned, but the oldest frames of a traceback are
792 returned. (This matches the behavior of the traceback module.)
793
794 .. method:: print_stack(\*, limit=None, file=None)
795
796 Print the stack or traceback for this Task.
797
798 This produces output similar to that of the traceback module
799 for the frames retrieved by :meth:`get_stack`.
800
801 The *limit* argument is passed to :meth:`get_stack` directly.
802
803 The *file* argument is an I/O stream to which the output
804 is written; by default output is written to :data:`sys.stderr`.
805
806 .. method:: get_name()
807
808 Return the name of the Task.
809
810 If no name has been explicitly assigned to the Task, the default
811 asyncio Task implementation generates a default name during
812 instantiation.
813
814 .. versionadded:: 3.8
815
816 .. method:: set_name(value)
817
818 Set the name of the Task.
819
820 The *value* argument can be any object, which is then
821 converted to a string.
822
823 In the default Task implementation, the name will be visible
824 in the :func:`repr` output of a task object.
825
826 .. versionadded:: 3.8
827
828 .. classmethod:: all_tasks(loop=None)
829
830 Return a set of all tasks for an event loop.
831
832 By default all tasks for the current event loop are returned.
833 If *loop* is ``None``, the :func:`get_event_loop` function
834 is used to get the current loop.
835
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400836 This method is **deprecated** and will be removed in
Yury Selivanovdb1a80e2018-09-21 16:23:15 -0400837 Python 3.9. Use the :func:`asyncio.all_tasks` function instead.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700838
839 .. classmethod:: current_task(loop=None)
840
841 Return the currently running task or ``None``.
842
843 If *loop* is ``None``, the :func:`get_event_loop` function
844 is used to get the current loop.
845
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400846 This method is **deprecated** and will be removed in
Yury Selivanovdb1a80e2018-09-21 16:23:15 -0400847 Python 3.9. Use the :func:`asyncio.current_task` function
848 instead.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700849
850
851.. _asyncio_generator_based_coro:
852
853Generator-based Coroutines
854==========================
855
856.. note::
857
858 Support for generator-based coroutines is **deprecated** and
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400859 is scheduled for removal in Python 4.0.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700860
861Generator-based coroutines predate async/await syntax. They are
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400862Python generators that use ``yield from`` expressions to await
Yury Selivanov3faaa882018-09-14 13:32:07 -0700863on Futures and other coroutines.
864
865Generator-based coroutines should be decorated with
866:func:`@asyncio.coroutine <asyncio.coroutine>`, although this is not
867enforced.
868
869
870.. decorator:: coroutine
871
872 Decorator to mark generator-based coroutines.
873
874 This decorator enables legacy generator-based coroutines to be
875 compatible with async/await code::
876
877 @asyncio.coroutine
878 def old_style_coroutine():
879 yield from asyncio.sleep(1)
880
881 async def main():
882 await old_style_coroutine()
883
884 This decorator is **deprecated** and is scheduled for removal in
885 Python 4.0.
886
887 This decorator should not be used for :keyword:`async def`
888 coroutines.
889
890.. function:: iscoroutine(obj)
891
892 Return ``True`` if *obj* is a :ref:`coroutine object <coroutine>`.
893
894 This method is different from :func:`inspect.iscoroutine` because
895 it returns ``True`` for generator-based coroutines decorated with
896 :func:`@coroutine <coroutine>`.
897
898.. function:: iscoroutinefunction(func)
899
900 Return ``True`` if *func* is a :ref:`coroutine function
901 <coroutine>`.
902
903 This method is different from :func:`inspect.iscoroutinefunction`
904 because it returns ``True`` for generator-based coroutine functions
905 decorated with :func:`@coroutine <coroutine>`.