blob: 3f54ecb08efc1f8059c864186c44f6cf1d7ddbf4 [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
Kyle Stanleyf9000642019-10-10 19:18:46 -040021:term:`Coroutines <coroutine>` declared with the async/await syntax is the
22preferred way of writing asyncio applications. For example, the following
23snippet of code (requires Python 3.7+) prints "hello", waits 1 second,
Yury Selivanovb042cf12018-09-18 02:47:54 -040024and 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
Boštjan Mejak1d5bdef2019-05-19 11:01:36 +020043To 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():
Mariatta9f43fbb2018-10-24 15:37:12 -070060 print(f"started at {time.strftime('%X')}")
Yury Selivanov3faaa882018-09-14 13:32:07 -070061
62 await say_after(1, 'hello')
63 await say_after(2, 'world')
64
Mariatta9f43fbb2018-10-24 15:37:12 -070065 print(f"finished at {time.strftime('%X')}")
Yury Selivanov3faaa882018-09-14 13:32:07 -070066
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
Mariatta9f43fbb2018-10-24 15:37:12 -070089 print(f"started at {time.strftime('%X')}")
Yury Selivanov3faaa882018-09-14 13:32:07 -070090
91 # Wait until both tasks are completed (should take
92 # around 2 seconds.)
93 await task1
94 await task2
95
Mariatta9f43fbb2018-10-24 15:37:12 -070096 print(f"finished at {time.strftime('%X')}")
Yury Selivanov3faaa882018-09-14 13:32:07 -070097
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
Andre Delfinodcc997c2020-12-16 22:37:28 -0300213.. function:: run(coro, *, debug=False)
Yury Selivanov02a0a192017-12-14 09:42:21 -0500214
Kyle Stanleye4070132019-09-30 20:12:21 -0400215 Execute the :term:`coroutine` *coro* and return the result.
216
Yury Selivanov02a0a192017-12-14 09:42:21 -0500217 This function runs the passed coroutine, taking care of
Kyle Stanley9fdc64c2019-09-19 08:47:22 -0400218 managing the asyncio event loop, *finalizing asynchronous
219 generators*, and closing the threadpool.
Yury Selivanov02a0a192017-12-14 09:42:21 -0500220
221 This function cannot be called when another asyncio event loop is
222 running in the same thread.
223
Yury Selivanov3faaa882018-09-14 13:32:07 -0700224 If *debug* is ``True``, the event loop will be run in debug mode.
Yury Selivanov02a0a192017-12-14 09:42:21 -0500225
226 This function always creates a new event loop and closes it at
227 the end. It should be used as a main entry point for asyncio
228 programs, and should ideally only be called once.
229
Emmanuel Arias17deb162019-09-25 05:53:49 -0300230 Example::
231
232 async def main():
233 await asyncio.sleep(1)
234 print('hello')
235
236 asyncio.run(main())
237
Yury Selivanov02a0a192017-12-14 09:42:21 -0500238 .. versionadded:: 3.7
239
Kyle Stanley9fdc64c2019-09-19 08:47:22 -0400240 .. versionchanged:: 3.9
241 Updated to use :meth:`loop.shutdown_default_executor`.
Yury Selivanov02a0a192017-12-14 09:42:21 -0500242
Kyle Stanleyf9000642019-10-10 19:18:46 -0400243 .. note::
244 The source code for ``asyncio.run()`` can be found in
245 :source:`Lib/asyncio/runners.py`.
246
Yury Selivanov3faaa882018-09-14 13:32:07 -0700247Creating Tasks
248==============
Victor Stinnerea3183f2013-12-03 01:08:00 +0100249
Andre Delfinodcc997c2020-12-16 22:37:28 -0300250.. function:: create_task(coro, *, name=None)
Andrew Svetlovf74ef452017-12-15 07:04:38 +0200251
Yury Selivanove247b462018-09-20 12:43:59 -0400252 Wrap the *coro* :ref:`coroutine <coroutine>` into a :class:`Task`
253 and schedule its execution. Return the Task object.
Alex Grönholmcca4eec2018-08-09 00:06:47 +0300254
255 If *name* is not ``None``, it is set as the name of the task using
256 :meth:`Task.set_name`.
Andrew Svetlovf74ef452017-12-15 07:04:38 +0200257
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400258 The task is executed in the loop returned by :func:`get_running_loop`,
Andrew Svetlovf74ef452017-12-15 07:04:38 +0200259 :exc:`RuntimeError` is raised if there is no running loop in
260 current thread.
261
Yury Selivanov47150392018-09-18 17:55:44 -0400262 This function has been **added in Python 3.7**. Prior to
263 Python 3.7, the low-level :func:`asyncio.ensure_future` function
264 can be used instead::
265
266 async def coro():
267 ...
268
269 # In Python 3.7+
270 task = asyncio.create_task(coro())
271 ...
272
273 # This works in all Python versions but is less readable
274 task = asyncio.ensure_future(coro())
275 ...
276
Andrew Svetlovf74ef452017-12-15 07:04:38 +0200277 .. versionadded:: 3.7
278
Alex Grönholmcca4eec2018-08-09 00:06:47 +0300279 .. versionchanged:: 3.8
280 Added the ``name`` parameter.
281
Victor Stinnerea3183f2013-12-03 01:08:00 +0100282
Yury Selivanov3faaa882018-09-14 13:32:07 -0700283Sleeping
284========
Andrew Svetlovf1240162016-01-11 14:40:35 +0200285
Yurii Karabas86150d32020-11-29 14:50:57 +0200286.. coroutinefunction:: sleep(delay, result=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100287
Yury Selivanov3faaa882018-09-14 13:32:07 -0700288 Block for *delay* seconds.
289
290 If *result* is provided, it is returned to the caller
Eli Bendersky2d26af82014-01-20 06:59:23 -0800291 when the coroutine completes.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100292
Hrvoje Nikšićcd602b82018-10-01 12:09:38 +0200293 ``sleep()`` always suspends the current task, allowing other tasks
294 to run.
295
Simon Willison5c301452021-01-06 18:03:18 -0800296 Setting the delay to 0 provides an optimized path to allow other
297 tasks to run. This can be used by long-running functions to avoid
298 blocking the event loop for the full duration of the function call.
299
Yury Selivanov7372c3b2018-09-14 15:11:24 -0700300 .. _asyncio_example_sleep:
Victor Stinner45b27ed2014-02-01 02:36:43 +0100301
Yury Selivanov3faaa882018-09-14 13:32:07 -0700302 Example of coroutine displaying the current date every second
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400303 for 5 seconds::
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100304
Yury Selivanov3faaa882018-09-14 13:32:07 -0700305 import asyncio
306 import datetime
Victor Stinnerea3183f2013-12-03 01:08:00 +0100307
Yury Selivanov3faaa882018-09-14 13:32:07 -0700308 async def display_date():
309 loop = asyncio.get_running_loop()
310 end_time = loop.time() + 5.0
311 while True:
312 print(datetime.datetime.now())
313 if (loop.time() + 1.0) >= end_time:
314 break
315 await asyncio.sleep(1)
316
317 asyncio.run(display_date())
318
319
320Running Tasks Concurrently
321==========================
322
Andre Delfinodcc997c2020-12-16 22:37:28 -0300323.. awaitablefunction:: gather(*aws, return_exceptions=False)
Yury Selivanov3faaa882018-09-14 13:32:07 -0700324
Yury Selivanove247b462018-09-20 12:43:59 -0400325 Run :ref:`awaitable objects <asyncio-awaitables>` in the *aws*
Yury Selivanov47150392018-09-18 17:55:44 -0400326 sequence *concurrently*.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700327
Yury Selivanove247b462018-09-20 12:43:59 -0400328 If any awaitable in *aws* is a coroutine, it is automatically
Yury Selivanov47150392018-09-18 17:55:44 -0400329 scheduled as a Task.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700330
Yury Selivanov47150392018-09-18 17:55:44 -0400331 If all awaitables are completed successfully, the result is an
332 aggregate list of returned values. The order of result values
Yury Selivanove247b462018-09-20 12:43:59 -0400333 corresponds to the order of awaitables in *aws*.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700334
Yury Selivanovdb1a80e2018-09-21 16:23:15 -0400335 If *return_exceptions* is ``False`` (default), the first
336 raised exception is immediately propagated to the task that
337 awaits on ``gather()``. Other awaitables in the *aws* sequence
338 **won't be cancelled** and will continue to run.
339
Yury Selivanov47150392018-09-18 17:55:44 -0400340 If *return_exceptions* is ``True``, exceptions are treated the
341 same as successful results, and aggregated in the result list.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700342
Yury Selivanovdb1a80e2018-09-21 16:23:15 -0400343 If ``gather()`` is *cancelled*, all submitted awaitables
Yury Selivanov3faaa882018-09-14 13:32:07 -0700344 (that have not completed yet) are also *cancelled*.
345
Yury Selivanove247b462018-09-20 12:43:59 -0400346 If any Task or Future from the *aws* sequence is *cancelled*, it is
Yury Selivanov47150392018-09-18 17:55:44 -0400347 treated as if it raised :exc:`CancelledError` -- the ``gather()``
348 call is **not** cancelled in this case. This is to prevent the
349 cancellation of one submitted Task/Future to cause other
350 Tasks/Futures to be cancelled.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700351
Yury Selivanov7372c3b2018-09-14 15:11:24 -0700352 .. _asyncio_example_gather:
353
Yury Selivanov3faaa882018-09-14 13:32:07 -0700354 Example::
355
356 import asyncio
357
358 async def factorial(name, number):
359 f = 1
360 for i in range(2, number + 1):
361 print(f"Task {name}: Compute factorial({i})...")
362 await asyncio.sleep(1)
363 f *= i
364 print(f"Task {name}: factorial({number}) = {f}")
365
366 async def main():
Yury Selivanov47150392018-09-18 17:55:44 -0400367 # Schedule three calls *concurrently*:
Yury Selivanov3faaa882018-09-14 13:32:07 -0700368 await asyncio.gather(
369 factorial("A", 2),
370 factorial("B", 3),
371 factorial("C", 4),
Miguel Ángel García9c53fa62018-09-18 08:01:26 +0200372 )
Yury Selivanov3faaa882018-09-14 13:32:07 -0700373
374 asyncio.run(main())
375
376 # Expected output:
377 #
378 # Task A: Compute factorial(2)...
379 # Task B: Compute factorial(2)...
380 # Task C: Compute factorial(2)...
381 # Task A: factorial(2) = 2
382 # Task B: Compute factorial(3)...
383 # Task C: Compute factorial(3)...
384 # Task B: factorial(3) = 6
385 # Task C: Compute factorial(4)...
386 # Task C: factorial(4) = 24
387
Vinay Sharmad42528a2020-07-20 14:12:57 +0530388 .. note::
389 If *return_exceptions* is False, cancelling gather() after it
390 has been marked done won't cancel any submitted awaitables.
391 For instance, gather can be marked done after propagating an
392 exception to the caller, therefore, calling ``gather.cancel()``
393 after catching an exception (raised by one of the awaitables) from
394 gather won't cancel any other awaitables.
395
Yury Selivanov47150392018-09-18 17:55:44 -0400396 .. versionchanged:: 3.7
397 If the *gather* itself is cancelled, the cancellation is
398 propagated regardless of *return_exceptions*.
399
Serhiy Storchaka172c0f22021-04-25 13:40:44 +0300400 .. deprecated:: 3.10
401 Deprecation warning is emitted if no positional arguments are provided
402 or not all positional arguments are Future-like objects
403 and there is no running event loop.
404
Yury Selivanov3faaa882018-09-14 13:32:07 -0700405
Yury Selivanovdb1a80e2018-09-21 16:23:15 -0400406Shielding From Cancellation
407===========================
Yury Selivanov3faaa882018-09-14 13:32:07 -0700408
Yurii Karabas86150d32020-11-29 14:50:57 +0200409.. awaitablefunction:: shield(aw)
Yury Selivanov3faaa882018-09-14 13:32:07 -0700410
Yury Selivanov47150392018-09-18 17:55:44 -0400411 Protect an :ref:`awaitable object <asyncio-awaitables>`
412 from being :meth:`cancelled <Task.cancel>`.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700413
Yury Selivanovdb1a80e2018-09-21 16:23:15 -0400414 If *aw* is a coroutine it is automatically scheduled as a Task.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100415
416 The statement::
417
Andrew Svetlov88743422017-12-11 17:35:49 +0200418 res = await shield(something())
Victor Stinnerea3183f2013-12-03 01:08:00 +0100419
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400420 is equivalent to::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100421
Andrew Svetlov88743422017-12-11 17:35:49 +0200422 res = await something()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100423
Yury Selivanov3faaa882018-09-14 13:32:07 -0700424 *except* that if the coroutine containing it is cancelled, the
425 Task running in ``something()`` is not cancelled. From the point
426 of view of ``something()``, the cancellation did not happen.
427 Although its caller is still cancelled, so the "await" expression
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400428 still raises a :exc:`CancelledError`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100429
Yury Selivanov3faaa882018-09-14 13:32:07 -0700430 If ``something()`` is cancelled by other means (i.e. from within
431 itself) that would also cancel ``shield()``.
432
433 If it is desired to completely ignore cancellation (not recommended)
434 the ``shield()`` function should be combined with a try/except
435 clause, as follows::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100436
437 try:
Andrew Svetlov88743422017-12-11 17:35:49 +0200438 res = await shield(something())
Victor Stinnerea3183f2013-12-03 01:08:00 +0100439 except CancelledError:
440 res = None
441
Serhiy Storchaka172c0f22021-04-25 13:40:44 +0300442 .. deprecated:: 3.10
443 Deprecation warning is emitted if *aw* is not Future-like object
444 and there is no running event loop.
445
Yury Selivanov950204d2016-05-16 16:23:00 -0400446
Yury Selivanov3faaa882018-09-14 13:32:07 -0700447Timeouts
448========
449
Yurii Karabas86150d32020-11-29 14:50:57 +0200450.. coroutinefunction:: wait_for(aw, timeout)
Yury Selivanov3faaa882018-09-14 13:32:07 -0700451
Yury Selivanove247b462018-09-20 12:43:59 -0400452 Wait for the *aw* :ref:`awaitable <asyncio-awaitables>`
Yury Selivanov47150392018-09-18 17:55:44 -0400453 to complete with a timeout.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700454
Yury Selivanove247b462018-09-20 12:43:59 -0400455 If *aw* is a coroutine it is automatically scheduled as a Task.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700456
457 *timeout* can either be ``None`` or a float or int number of seconds
458 to wait for. If *timeout* is ``None``, block until the future
459 completes.
460
461 If a timeout occurs, it cancels the task and raises
462 :exc:`asyncio.TimeoutError`.
463
Yury Selivanov47150392018-09-18 17:55:44 -0400464 To avoid the task :meth:`cancellation <Task.cancel>`,
465 wrap it in :func:`shield`.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700466
467 The function will wait until the future is actually cancelled,
romasku382a5632020-05-15 23:12:05 +0300468 so the total wait time may exceed the *timeout*. If an exception
469 happens during cancellation, it is propagated.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700470
Yury Selivanove247b462018-09-20 12:43:59 -0400471 If the wait is cancelled, the future *aw* is also cancelled.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700472
Yury Selivanov7372c3b2018-09-14 15:11:24 -0700473 .. _asyncio_example_waitfor:
474
Yury Selivanov3faaa882018-09-14 13:32:07 -0700475 Example::
476
477 async def eternity():
478 # Sleep for one hour
479 await asyncio.sleep(3600)
480 print('yay!')
481
482 async def main():
483 # Wait for at most 1 second
484 try:
485 await asyncio.wait_for(eternity(), timeout=1.0)
486 except asyncio.TimeoutError:
487 print('timeout!')
488
489 asyncio.run(main())
490
491 # Expected output:
492 #
493 # timeout!
494
495 .. versionchanged:: 3.7
Yury Selivanove247b462018-09-20 12:43:59 -0400496 When *aw* is cancelled due to a timeout, ``wait_for`` waits
497 for *aw* to be cancelled. Previously, it raised
Yury Selivanov3faaa882018-09-14 13:32:07 -0700498 :exc:`asyncio.TimeoutError` immediately.
499
500
501Waiting Primitives
502==================
503
Andre Delfinodcc997c2020-12-16 22:37:28 -0300504.. coroutinefunction:: wait(aws, *, timeout=None, return_when=ALL_COMPLETED)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100505
Yury Selivanove247b462018-09-20 12:43:59 -0400506 Run :ref:`awaitable objects <asyncio-awaitables>` in the *aws*
Jakub Stasiak3d86d092020-11-02 11:56:35 +0100507 iterable concurrently and block until the condition specified
Yury Selivanov47150392018-09-18 17:55:44 -0400508 by *return_when*.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100509
Jakub Stasiak3d86d092020-11-02 11:56:35 +0100510 The *aws* iterable must not be empty.
Joel Rosdahl9d746582020-05-04 23:56:00 +0200511
Yury Selivanov3faaa882018-09-14 13:32:07 -0700512 Returns two sets of Tasks/Futures: ``(done, pending)``.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100513
Yury Selivanov996859a2018-09-25 14:51:21 -0400514 Usage::
515
516 done, pending = await asyncio.wait(aws)
517
Yury Selivanov3faaa882018-09-14 13:32:07 -0700518 *timeout* (a float or int), if specified, can be used to control
519 the maximum number of seconds to wait before returning.
520
521 Note that this function does not raise :exc:`asyncio.TimeoutError`.
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400522 Futures or Tasks that aren't done when the timeout occurs are simply
Yury Selivanov3faaa882018-09-14 13:32:07 -0700523 returned in the second set.
524
525 *return_when* indicates when this function should return. It must
526 be one of the following constants:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100527
528 .. tabularcolumns:: |l|L|
529
530 +-----------------------------+----------------------------------------+
531 | Constant | Description |
532 +=============================+========================================+
533 | :const:`FIRST_COMPLETED` | The function will return when any |
534 | | future finishes or is cancelled. |
535 +-----------------------------+----------------------------------------+
536 | :const:`FIRST_EXCEPTION` | The function will return when any |
537 | | future finishes by raising an |
538 | | exception. If no future raises an |
539 | | exception then it is equivalent to |
540 | | :const:`ALL_COMPLETED`. |
541 +-----------------------------+----------------------------------------+
542 | :const:`ALL_COMPLETED` | The function will return when all |
543 | | futures finish or are cancelled. |
544 +-----------------------------+----------------------------------------+
545
Yury Selivanov3faaa882018-09-14 13:32:07 -0700546 Unlike :func:`~asyncio.wait_for`, ``wait()`` does not cancel the
547 futures when a timeout occurs.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100548
Andrew Svetlova4888792019-09-12 15:40:40 +0300549 .. deprecated:: 3.8
550
551 If any awaitable in *aws* is a coroutine, it is automatically
552 scheduled as a Task. Passing coroutines objects to
553 ``wait()`` directly is deprecated as it leads to
554 :ref:`confusing behavior <asyncio_example_wait_coroutine>`.
555
Yury Selivanov996859a2018-09-25 14:51:21 -0400556 .. _asyncio_example_wait_coroutine:
557 .. note::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100558
Yury Selivanov996859a2018-09-25 14:51:21 -0400559 ``wait()`` schedules coroutines as Tasks automatically and later
560 returns those implicitly created Task objects in ``(done, pending)``
561 sets. Therefore the following code won't work as expected::
562
563 async def foo():
564 return 42
565
566 coro = foo()
567 done, pending = await asyncio.wait({coro})
568
569 if coro in done:
570 # This branch will never be run!
571
572 Here is how the above snippet can be fixed::
573
574 async def foo():
575 return 42
576
577 task = asyncio.create_task(foo())
578 done, pending = await asyncio.wait({task})
579
580 if task in done:
581 # Everything will work as expected now.
582
jack1142de927692020-05-13 20:55:12 +0200583 .. deprecated-removed:: 3.8 3.11
Matthias Bussonnierd0ebf132019-05-20 23:20:10 -0700584
Yury Selivanov996859a2018-09-25 14:51:21 -0400585 Passing coroutine objects to ``wait()`` directly is
586 deprecated.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100587
Victor Stinnerea3183f2013-12-03 01:08:00 +0100588
Andre Delfinodcc997c2020-12-16 22:37:28 -0300589.. function:: as_completed(aws, *, timeout=None)
Yury Selivanov3faaa882018-09-14 13:32:07 -0700590
Yury Selivanove247b462018-09-20 12:43:59 -0400591 Run :ref:`awaitable objects <asyncio-awaitables>` in the *aws*
Jakub Stasiak3d86d092020-11-02 11:56:35 +0100592 iterable concurrently. Return an iterator of coroutines.
Bar Harel13206b52020-05-24 02:14:31 +0300593 Each coroutine returned can be awaited to get the earliest next
Jakub Stasiak3d86d092020-11-02 11:56:35 +0100594 result from the iterable of the remaining awaitables.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700595
596 Raises :exc:`asyncio.TimeoutError` if the timeout occurs before
597 all Futures are done.
598
599 Example::
600
Bar Harel13206b52020-05-24 02:14:31 +0300601 for coro in as_completed(aws):
602 earliest_result = await coro
Yury Selivanov3faaa882018-09-14 13:32:07 -0700603 # ...
Victor Stinnerea3183f2013-12-03 01:08:00 +0100604
Serhiy Storchaka172c0f22021-04-25 13:40:44 +0300605 .. deprecated:: 3.10
606 Deprecation warning is emitted if not all awaitable objects in the *aws*
607 iterable are Future-like objects and there is no running event loop.
608
Victor Stinner3e09e322013-12-03 01:22:06 +0100609
Kyle Stanleycc2bbc22020-05-18 23:03:28 -0400610Running in Threads
611==================
612
Andre Delfinodcc997c2020-12-16 22:37:28 -0300613.. coroutinefunction:: to_thread(func, /, *args, **kwargs)
Kyle Stanleycc2bbc22020-05-18 23:03:28 -0400614
615 Asynchronously run function *func* in a separate thread.
616
617 Any \*args and \*\*kwargs supplied for this function are directly passed
Jesús Cea989af252020-11-24 00:56:30 +0100618 to *func*. Also, the current :class:`contextvars.Context` is propagated,
Kyle Stanley0f562632020-05-21 01:20:43 -0400619 allowing context variables from the event loop thread to be accessed in the
620 separate thread.
Kyle Stanleycc2bbc22020-05-18 23:03:28 -0400621
Kyle Stanley2b201362020-05-31 03:07:04 -0400622 Return a coroutine that can be awaited to get the eventual result of *func*.
Kyle Stanleycc2bbc22020-05-18 23:03:28 -0400623
624 This coroutine function is primarily intended to be used for executing
625 IO-bound functions/methods that would otherwise block the event loop if
626 they were ran in the main thread. For example::
627
628 def blocking_io():
629 print(f"start blocking_io at {time.strftime('%X')}")
630 # Note that time.sleep() can be replaced with any blocking
631 # IO-bound operation, such as file operations.
632 time.sleep(1)
633 print(f"blocking_io complete at {time.strftime('%X')}")
634
635 async def main():
636 print(f"started main at {time.strftime('%X')}")
637
638 await asyncio.gather(
639 asyncio.to_thread(blocking_io),
640 asyncio.sleep(1))
641
642 print(f"finished main at {time.strftime('%X')}")
643
644
645 asyncio.run(main())
646
647 # Expected output:
648 #
649 # started main at 19:50:53
650 # start blocking_io at 19:50:53
651 # blocking_io complete at 19:50:54
652 # finished main at 19:50:54
653
654 Directly calling `blocking_io()` in any coroutine would block the event loop
655 for its duration, resulting in an additional 1 second of run time. Instead,
656 by using `asyncio.to_thread()`, we can run it in a separate thread without
657 blocking the event loop.
658
659 .. note::
660
661 Due to the :term:`GIL`, `asyncio.to_thread()` can typically only be used
662 to make IO-bound functions non-blocking. However, for extension modules
663 that release the GIL or alternative Python implementations that don't
664 have one, `asyncio.to_thread()` can also be used for CPU-bound functions.
665
Kyle Stanley0f562632020-05-21 01:20:43 -0400666 .. versionadded:: 3.9
667
Kyle Stanleycc2bbc22020-05-18 23:03:28 -0400668
Yury Selivanov3faaa882018-09-14 13:32:07 -0700669Scheduling From Other Threads
670=============================
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100671
Yury Selivanov3faaa882018-09-14 13:32:07 -0700672.. function:: run_coroutine_threadsafe(coro, loop)
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100673
Yury Selivanov3faaa882018-09-14 13:32:07 -0700674 Submit a coroutine to the given event loop. Thread-safe.
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100675
Yury Selivanov47150392018-09-18 17:55:44 -0400676 Return a :class:`concurrent.futures.Future` to wait for the result
677 from another OS thread.
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100678
Yury Selivanov3faaa882018-09-14 13:32:07 -0700679 This function is meant to be called from a different OS thread
680 than the one where the event loop is running. Example::
Victor Stinner72dcb0a2015-04-03 17:08:19 +0200681
Yury Selivanov3faaa882018-09-14 13:32:07 -0700682 # Create a coroutine
683 coro = asyncio.sleep(1, result=3)
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500684
Yury Selivanov3faaa882018-09-14 13:32:07 -0700685 # Submit the coroutine to a given loop
686 future = asyncio.run_coroutine_threadsafe(coro, loop)
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100687
Yury Selivanov3faaa882018-09-14 13:32:07 -0700688 # Wait for the result with an optional timeout argument
689 assert future.result(timeout) == 3
690
691 If an exception is raised in the coroutine, the returned Future
692 will be notified. It can also be used to cancel the task in
693 the event loop::
694
695 try:
696 result = future.result(timeout)
697 except asyncio.TimeoutError:
698 print('The coroutine took too long, cancelling the task...')
699 future.cancel()
700 except Exception as exc:
Mariatta9f43fbb2018-10-24 15:37:12 -0700701 print(f'The coroutine raised an exception: {exc!r}')
Yury Selivanov3faaa882018-09-14 13:32:07 -0700702 else:
Mariatta9f43fbb2018-10-24 15:37:12 -0700703 print(f'The coroutine returned: {result!r}')
Yury Selivanov3faaa882018-09-14 13:32:07 -0700704
705 See the :ref:`concurrency and multithreading <asyncio-multithreading>`
706 section of the documentation.
707
Vaibhav Gupta3a810762018-12-26 20:17:17 +0530708 Unlike other asyncio functions this function requires the *loop*
Yury Selivanov3faaa882018-09-14 13:32:07 -0700709 argument to be passed explicitly.
710
711 .. versionadded:: 3.5.1
712
713
714Introspection
715=============
716
717
718.. function:: current_task(loop=None)
719
720 Return the currently running :class:`Task` instance, or ``None`` if
721 no task is running.
722
723 If *loop* is ``None`` :func:`get_running_loop` is used to get
724 the current loop.
725
726 .. versionadded:: 3.7
727
728
729.. function:: all_tasks(loop=None)
730
731 Return a set of not yet finished :class:`Task` objects run by
732 the loop.
733
734 If *loop* is ``None``, :func:`get_running_loop` is used for getting
735 current loop.
736
737 .. versionadded:: 3.7
738
739
740Task Object
741===========
742
Andre Delfinodcc997c2020-12-16 22:37:28 -0300743.. class:: Task(coro, *, loop=None, name=None)
Yury Selivanov3faaa882018-09-14 13:32:07 -0700744
Yury Selivanovdb1a80e2018-09-21 16:23:15 -0400745 A :class:`Future-like <Future>` object that runs a Python
Yury Selivanov3faaa882018-09-14 13:32:07 -0700746 :ref:`coroutine <coroutine>`. Not thread-safe.
747
748 Tasks are used to run coroutines in event loops.
749 If a coroutine awaits on a Future, the Task suspends
750 the execution of the coroutine and waits for the completion
751 of the Future. When the Future is *done*, the execution of
752 the wrapped coroutine resumes.
753
754 Event loops use cooperative scheduling: an event loop runs
755 one Task at a time. While a Task awaits for the completion of a
756 Future, the event loop runs other Tasks, callbacks, or performs
757 IO operations.
758
759 Use the high-level :func:`asyncio.create_task` function to create
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400760 Tasks, or the low-level :meth:`loop.create_task` or
761 :func:`ensure_future` functions. Manual instantiation of Tasks
762 is discouraged.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700763
764 To cancel a running Task use the :meth:`cancel` method. Calling it
765 will cause the Task to throw a :exc:`CancelledError` exception into
766 the wrapped coroutine. If a coroutine is awaiting on a Future
767 object during cancellation, the Future object will be cancelled.
768
769 :meth:`cancelled` can be used to check if the Task was cancelled.
770 The method returns ``True`` if the wrapped coroutine did not
771 suppress the :exc:`CancelledError` exception and was actually
772 cancelled.
773
774 :class:`asyncio.Task` inherits from :class:`Future` all of its
775 APIs except :meth:`Future.set_result` and
776 :meth:`Future.set_exception`.
777
778 Tasks support the :mod:`contextvars` module. When a Task
779 is created it copies the current context and later runs its
780 coroutine in the copied context.
Elvis Pranskevichuse2b340a2018-05-29 17:31:01 -0400781
782 .. versionchanged:: 3.7
Yury Selivanov3faaa882018-09-14 13:32:07 -0700783 Added support for the :mod:`contextvars` module.
784
785 .. versionchanged:: 3.8
786 Added the ``name`` parameter.
787
Andrew Svetlova4888792019-09-12 15:40:40 +0300788 .. deprecated-removed:: 3.8 3.10
789 The *loop* parameter.
790
Serhiy Storchaka172c0f22021-04-25 13:40:44 +0300791 .. deprecated:: 3.10
792 Deprecation warning is emitted if *loop* is not specified
793 and there is no running event loop.
794
Chris Jerdonek1ce58412020-05-15 16:55:50 -0700795 .. method:: cancel(msg=None)
Yury Selivanov3faaa882018-09-14 13:32:07 -0700796
797 Request the Task to be cancelled.
798
799 This arranges for a :exc:`CancelledError` exception to be thrown
800 into the wrapped coroutine on the next cycle of the event loop.
801
802 The coroutine then has a chance to clean up or even deny the
803 request by suppressing the exception with a :keyword:`try` ...
804 ... ``except CancelledError`` ... :keyword:`finally` block.
805 Therefore, unlike :meth:`Future.cancel`, :meth:`Task.cancel` does
806 not guarantee that the Task will be cancelled, although
807 suppressing cancellation completely is not common and is actively
808 discouraged.
809
Chris Jerdonek1ce58412020-05-15 16:55:50 -0700810 .. versionchanged:: 3.9
811 Added the ``msg`` parameter.
812
Yury Selivanov7372c3b2018-09-14 15:11:24 -0700813 .. _asyncio_example_task_cancel:
814
Yury Selivanov3faaa882018-09-14 13:32:07 -0700815 The following example illustrates how coroutines can intercept
816 the cancellation request::
817
818 async def cancel_me():
819 print('cancel_me(): before sleep')
820
821 try:
822 # Wait for 1 hour
823 await asyncio.sleep(3600)
824 except asyncio.CancelledError:
825 print('cancel_me(): cancel sleep')
826 raise
827 finally:
828 print('cancel_me(): after sleep')
829
830 async def main():
831 # Create a "cancel_me" Task
832 task = asyncio.create_task(cancel_me())
833
834 # Wait for 1 second
835 await asyncio.sleep(1)
836
837 task.cancel()
838 try:
839 await task
840 except asyncio.CancelledError:
841 print("main(): cancel_me is cancelled now")
842
843 asyncio.run(main())
844
845 # Expected output:
846 #
847 # cancel_me(): before sleep
848 # cancel_me(): cancel sleep
849 # cancel_me(): after sleep
850 # main(): cancel_me is cancelled now
851
852 .. method:: cancelled()
853
854 Return ``True`` if the Task is *cancelled*.
855
856 The Task is *cancelled* when the cancellation was requested with
857 :meth:`cancel` and the wrapped coroutine propagated the
858 :exc:`CancelledError` exception thrown into it.
859
860 .. method:: done()
861
862 Return ``True`` if the Task is *done*.
863
864 A Task is *done* when the wrapped coroutine either returned
865 a value, raised an exception, or the Task was cancelled.
866
Yury Selivanove247b462018-09-20 12:43:59 -0400867 .. method:: result()
868
869 Return the result of the Task.
870
871 If the Task is *done*, the result of the wrapped coroutine
872 is returned (or if the coroutine raised an exception, that
873 exception is re-raised.)
874
875 If the Task has been *cancelled*, this method raises
876 a :exc:`CancelledError` exception.
877
878 If the Task's result isn't yet available, this method raises
879 a :exc:`InvalidStateError` exception.
880
881 .. method:: exception()
882
883 Return the exception of the Task.
884
885 If the wrapped coroutine raised an exception that exception
886 is returned. If the wrapped coroutine returned normally
887 this method returns ``None``.
888
889 If the Task has been *cancelled*, this method raises a
890 :exc:`CancelledError` exception.
891
892 If the Task isn't *done* yet, this method raises an
893 :exc:`InvalidStateError` exception.
894
895 .. method:: add_done_callback(callback, *, context=None)
896
897 Add a callback to be run when the Task is *done*.
898
899 This method should only be used in low-level callback-based code.
900
901 See the documentation of :meth:`Future.add_done_callback`
902 for more details.
903
904 .. method:: remove_done_callback(callback)
905
906 Remove *callback* from the callbacks list.
907
908 This method should only be used in low-level callback-based code.
909
910 See the documentation of :meth:`Future.remove_done_callback`
911 for more details.
912
Andre Delfinodcc997c2020-12-16 22:37:28 -0300913 .. method:: get_stack(*, limit=None)
Yury Selivanov3faaa882018-09-14 13:32:07 -0700914
915 Return the list of stack frames for this Task.
916
917 If the wrapped coroutine is not done, this returns the stack
918 where it is suspended. If the coroutine has completed
919 successfully or was cancelled, this returns an empty list.
920 If the coroutine was terminated by an exception, this returns
921 the list of traceback frames.
922
923 The frames are always ordered from oldest to newest.
924
925 Only one stack frame is returned for a suspended coroutine.
926
927 The optional *limit* argument sets the maximum number of frames
928 to return; by default all available frames are returned.
929 The ordering of the returned list differs depending on whether
930 a stack or a traceback is returned: the newest frames of a
931 stack are returned, but the oldest frames of a traceback are
932 returned. (This matches the behavior of the traceback module.)
933
Andre Delfinodcc997c2020-12-16 22:37:28 -0300934 .. method:: print_stack(*, limit=None, file=None)
Yury Selivanov3faaa882018-09-14 13:32:07 -0700935
936 Print the stack or traceback for this Task.
937
938 This produces output similar to that of the traceback module
939 for the frames retrieved by :meth:`get_stack`.
940
941 The *limit* argument is passed to :meth:`get_stack` directly.
942
943 The *file* argument is an I/O stream to which the output
944 is written; by default output is written to :data:`sys.stderr`.
945
Alex Grönholm98ef9202019-05-30 18:30:09 +0300946 .. method:: get_coro()
947
948 Return the coroutine object wrapped by the :class:`Task`.
949
950 .. versionadded:: 3.8
951
Yury Selivanov3faaa882018-09-14 13:32:07 -0700952 .. method:: get_name()
953
954 Return the name of the Task.
955
956 If no name has been explicitly assigned to the Task, the default
957 asyncio Task implementation generates a default name during
958 instantiation.
959
960 .. versionadded:: 3.8
961
962 .. method:: set_name(value)
963
964 Set the name of the Task.
965
966 The *value* argument can be any object, which is then
967 converted to a string.
968
969 In the default Task implementation, the name will be visible
970 in the :func:`repr` output of a task object.
971
972 .. versionadded:: 3.8
973
Yury Selivanov3faaa882018-09-14 13:32:07 -0700974
975.. _asyncio_generator_based_coro:
976
977Generator-based Coroutines
978==========================
979
980.. note::
981
982 Support for generator-based coroutines is **deprecated** and
Yury Selivanovfad6af22018-09-25 17:44:52 -0400983 is scheduled for removal in Python 3.10.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700984
985Generator-based coroutines predate async/await syntax. They are
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400986Python generators that use ``yield from`` expressions to await
Yury Selivanov3faaa882018-09-14 13:32:07 -0700987on Futures and other coroutines.
988
989Generator-based coroutines should be decorated with
990:func:`@asyncio.coroutine <asyncio.coroutine>`, although this is not
991enforced.
992
993
994.. decorator:: coroutine
995
996 Decorator to mark generator-based coroutines.
997
998 This decorator enables legacy generator-based coroutines to be
999 compatible with async/await code::
1000
1001 @asyncio.coroutine
1002 def old_style_coroutine():
1003 yield from asyncio.sleep(1)
1004
1005 async def main():
1006 await old_style_coroutine()
1007
Yury Selivanov3faaa882018-09-14 13:32:07 -07001008 This decorator should not be used for :keyword:`async def`
1009 coroutines.
1010
Andrew Svetlov68b34a72019-05-16 17:52:10 +03001011 .. deprecated-removed:: 3.8 3.10
1012
1013 Use :keyword:`async def` instead.
1014
Yury Selivanov3faaa882018-09-14 13:32:07 -07001015.. function:: iscoroutine(obj)
1016
1017 Return ``True`` if *obj* is a :ref:`coroutine object <coroutine>`.
1018
1019 This method is different from :func:`inspect.iscoroutine` because
Yury Selivanov59ee5b12018-09-27 15:48:30 -04001020 it returns ``True`` for generator-based coroutines.
Yury Selivanov3faaa882018-09-14 13:32:07 -07001021
1022.. function:: iscoroutinefunction(func)
1023
1024 Return ``True`` if *func* is a :ref:`coroutine function
1025 <coroutine>`.
1026
1027 This method is different from :func:`inspect.iscoroutinefunction`
1028 because it returns ``True`` for generator-based coroutine functions
1029 decorated with :func:`@coroutine <coroutine>`.