R David Murray | 6a14381 | 2013-12-20 14:37:39 -0500 | [diff] [blame] | 1 | .. currentmodule:: asyncio |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 2 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 3 | |
| 4 | ==================== |
| 5 | Coroutines and Tasks |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 6 | ==================== |
| 7 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 8 | This section outlines high-level asyncio APIs to work with coroutines |
| 9 | and Tasks. |
lf | 627d2c8 | 2017-07-25 17:03:51 -0600 | [diff] [blame] | 10 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 11 | .. contents:: |
| 12 | :depth: 1 |
| 13 | :local: |
| 14 | |
lf | 627d2c8 | 2017-07-25 17:03:51 -0600 | [diff] [blame] | 15 | |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 16 | .. _coroutine: |
| 17 | |
| 18 | Coroutines |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 19 | ========== |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 20 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 21 | Coroutines declared with async/await syntax is the preferred way of |
| 22 | writing asyncio applications. For example, the following snippet |
Yury Selivanov | b042cf1 | 2018-09-18 02:47:54 -0400 | [diff] [blame] | 23 | of code (requires Python 3.7+) prints "hello", waits 1 second, |
| 24 | and then prints "world":: |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 25 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 26 | >>> import asyncio |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 27 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 28 | >>> async def main(): |
| 29 | ... print('hello') |
| 30 | ... await asyncio.sleep(1) |
| 31 | ... print('world') |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 32 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 33 | >>> asyncio.run(main()) |
| 34 | hello |
| 35 | world |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 36 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 37 | Note that simply calling a coroutine will not schedule it to |
| 38 | be executed:: |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 39 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 40 | >>> main() |
| 41 | <coroutine object main at 0x1053bb7c8> |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 42 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 43 | To actually run a coroutine asyncio provides three main mechanisms: |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 44 | |
Elvis Pranskevichus | 1fa2ec4 | 2018-09-17 19:16:44 -0400 | [diff] [blame] | 45 | * The :func:`asyncio.run` function to run the top-level |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 46 | entry point "main()" function (see the above example.) |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 47 | |
Elvis Pranskevichus | 1fa2ec4 | 2018-09-17 19:16:44 -0400 | [diff] [blame] | 48 | * Awaiting on a coroutine. The following snippet of code will |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 49 | print "hello" after waiting for 1 second, and then print "world" |
| 50 | after waiting for *another* 2 seconds:: |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 51 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 52 | import asyncio |
| 53 | import time |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 54 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 55 | async def say_after(delay, what): |
| 56 | await asyncio.sleep(delay) |
| 57 | print(what) |
| 58 | |
| 59 | async def main(): |
Mariatta | 9f43fbb | 2018-10-24 15:37:12 -0700 | [diff] [blame] | 60 | print(f"started at {time.strftime('%X')}") |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 61 | |
| 62 | await say_after(1, 'hello') |
| 63 | await say_after(2, 'world') |
| 64 | |
Mariatta | 9f43fbb | 2018-10-24 15:37:12 -0700 | [diff] [blame] | 65 | print(f"finished at {time.strftime('%X')}") |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 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 Pranskevichus | 1fa2ec4 | 2018-09-17 19:16:44 -0400 | [diff] [blame] | 76 | * The :func:`asyncio.create_task` function to run coroutines |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 77 | concurrently as asyncio :class:`Tasks <Task>`. |
| 78 | |
Danny Hermes | 7bfbda4 | 2018-09-17 21:49:21 -0700 | [diff] [blame] | 79 | Let's modify the above example and run two ``say_after`` coroutines |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 80 | *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 | |
Mariatta | 9f43fbb | 2018-10-24 15:37:12 -0700 | [diff] [blame] | 89 | print(f"started at {time.strftime('%X')}") |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 90 | |
| 91 | # Wait until both tasks are completed (should take |
| 92 | # around 2 seconds.) |
| 93 | await task1 |
| 94 | await task2 |
| 95 | |
Mariatta | 9f43fbb | 2018-10-24 15:37:12 -0700 | [diff] [blame] | 96 | print(f"finished at {time.strftime('%X')}") |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 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 Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 106 | |
| 107 | .. _asyncio-awaitables: |
| 108 | |
| 109 | Awaitables |
| 110 | ========== |
| 111 | |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame] | 112 | We say that an object is an **awaitable** object if it can be used |
| 113 | in an :keyword:`await` expression. Many asyncio APIs are designed to |
| 114 | accept awaitables. |
| 115 | |
| 116 | There are three main types of *awaitable* objects: |
| 117 | **coroutines**, **Tasks**, and **Futures**. |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 118 | |
| 119 | |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame] | 120 | .. rubric:: Coroutines |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 121 | |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame] | 122 | Python coroutines are *awaitables* and therefore can be awaited from |
| 123 | other coroutines:: |
| 124 | |
| 125 | import asyncio |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 126 | |
| 127 | async def nested(): |
| 128 | return 42 |
| 129 | |
| 130 | async def main(): |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame] | 131 | # Nothing happens if we just call "nested()". |
Yury Selivanov | db1a80e | 2018-09-21 16:23:15 -0400 | [diff] [blame] | 132 | # A coroutine object is created but not awaited, |
| 133 | # so it *won't run at all*. |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame] | 134 | 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 | |
| 151 | asyncio also supports legacy :ref:`generator-based |
| 152 | <asyncio_generator_based_coro>` coroutines. |
| 153 | |
| 154 | |
| 155 | .. rubric:: Tasks |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 156 | |
| 157 | *Tasks* are used to schedule coroutines *concurrently*. |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 158 | |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame] | 159 | When a coroutine is wrapped into a *Task* with functions like |
| 160 | :func:`asyncio.create_task` the coroutine is automatically |
| 161 | scheduled to run soon:: |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 162 | |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame] | 163 | import asyncio |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 164 | |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame] | 165 | 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 Stinner | 337e03f | 2014-08-11 01:11:13 +0200 | [diff] [blame] | 178 | |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 179 | |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 180 | .. rubric:: Futures |
| 181 | |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame] | 182 | A :class:`Future` is a special **low-level** awaitable object that |
| 183 | represents an **eventual result** of an asynchronous operation. |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 184 | |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame] | 185 | When a Future object is *awaited* it means that the coroutine will |
| 186 | wait until the Future is resolved in some other place. |
| 187 | |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 188 | Future objects in asyncio are needed to allow callback-based code |
| 189 | to be used with async/await. |
| 190 | |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame] | 191 | Normally **there is no need** to create Future objects at the |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 192 | application level code. |
| 193 | |
| 194 | Future objects, sometimes exposed by libraries and some asyncio |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame] | 195 | APIs, can be awaited:: |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 196 | |
| 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 Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame] | 206 | A good example of a low-level function that returns a Future object |
| 207 | is :meth:`loop.run_in_executor`. |
| 208 | |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 209 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 210 | Running an asyncio Program |
| 211 | ========================== |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 212 | |
Elvis Pranskevichus | 63536bd | 2018-05-19 23:15:06 -0400 | [diff] [blame] | 213 | .. function:: run(coro, \*, debug=False) |
Yury Selivanov | 02a0a19 | 2017-12-14 09:42:21 -0500 | [diff] [blame] | 214 | |
| 215 | This function runs the passed coroutine, taking care of |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 216 | managing the asyncio event loop and *finalizing asynchronous |
| 217 | generators*. |
Yury Selivanov | 02a0a19 | 2017-12-14 09:42:21 -0500 | [diff] [blame] | 218 | |
| 219 | This function cannot be called when another asyncio event loop is |
| 220 | running in the same thread. |
| 221 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 222 | If *debug* is ``True``, the event loop will be run in debug mode. |
Yury Selivanov | 02a0a19 | 2017-12-14 09:42:21 -0500 | [diff] [blame] | 223 | |
| 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 Pranskevichus | 1fa2ec4 | 2018-09-17 19:16:44 -0400 | [diff] [blame] | 229 | **Important:** this function has been added to asyncio in |
| 230 | Python 3.7 on a :term:`provisional basis <provisional api>`. |
Yury Selivanov | 02a0a19 | 2017-12-14 09:42:21 -0500 | [diff] [blame] | 231 | |
| 232 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 233 | Creating Tasks |
| 234 | ============== |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 235 | |
Alex Grönholm | cca4eec | 2018-08-09 00:06:47 +0300 | [diff] [blame] | 236 | .. function:: create_task(coro, \*, name=None) |
Andrew Svetlov | f74ef45 | 2017-12-15 07:04:38 +0200 | [diff] [blame] | 237 | |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame] | 238 | Wrap the *coro* :ref:`coroutine <coroutine>` into a :class:`Task` |
| 239 | and schedule its execution. Return the Task object. |
Alex Grönholm | cca4eec | 2018-08-09 00:06:47 +0300 | [diff] [blame] | 240 | |
| 241 | If *name* is not ``None``, it is set as the name of the task using |
| 242 | :meth:`Task.set_name`. |
Andrew Svetlov | f74ef45 | 2017-12-15 07:04:38 +0200 | [diff] [blame] | 243 | |
Elvis Pranskevichus | 1fa2ec4 | 2018-09-17 19:16:44 -0400 | [diff] [blame] | 244 | The task is executed in the loop returned by :func:`get_running_loop`, |
Andrew Svetlov | f74ef45 | 2017-12-15 07:04:38 +0200 | [diff] [blame] | 245 | :exc:`RuntimeError` is raised if there is no running loop in |
| 246 | current thread. |
| 247 | |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 248 | 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 Svetlov | f74ef45 | 2017-12-15 07:04:38 +0200 | [diff] [blame] | 263 | .. versionadded:: 3.7 |
| 264 | |
Alex Grönholm | cca4eec | 2018-08-09 00:06:47 +0300 | [diff] [blame] | 265 | .. versionchanged:: 3.8 |
| 266 | Added the ``name`` parameter. |
| 267 | |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 268 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 269 | Sleeping |
| 270 | ======== |
Andrew Svetlov | f124016 | 2016-01-11 14:40:35 +0200 | [diff] [blame] | 271 | |
Victor Stinner | bdd574d | 2015-02-12 22:49:18 +0100 | [diff] [blame] | 272 | .. coroutinefunction:: sleep(delay, result=None, \*, loop=None) |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 273 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 274 | Block for *delay* seconds. |
| 275 | |
| 276 | If *result* is provided, it is returned to the caller |
Eli Bendersky | 2d26af8 | 2014-01-20 06:59:23 -0800 | [diff] [blame] | 277 | when the coroutine completes. |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 278 | |
Hrvoje Nikšić | cd602b8 | 2018-10-01 12:09:38 +0200 | [diff] [blame] | 279 | ``sleep()`` always suspends the current task, allowing other tasks |
| 280 | to run. |
| 281 | |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 282 | The *loop* argument is deprecated and scheduled for removal |
Yury Selivanov | fad6af2 | 2018-09-25 17:44:52 -0400 | [diff] [blame] | 283 | in Python 3.10. |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 284 | |
Yury Selivanov | 7372c3b | 2018-09-14 15:11:24 -0700 | [diff] [blame] | 285 | .. _asyncio_example_sleep: |
Victor Stinner | 45b27ed | 2014-02-01 02:36:43 +0100 | [diff] [blame] | 286 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 287 | Example of coroutine displaying the current date every second |
Elvis Pranskevichus | 1fa2ec4 | 2018-09-17 19:16:44 -0400 | [diff] [blame] | 288 | for 5 seconds:: |
Victor Stinner | bdd574d | 2015-02-12 22:49:18 +0100 | [diff] [blame] | 289 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 290 | import asyncio |
| 291 | import datetime |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 292 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 293 | async def display_date(): |
| 294 | loop = asyncio.get_running_loop() |
| 295 | end_time = loop.time() + 5.0 |
| 296 | while True: |
| 297 | print(datetime.datetime.now()) |
| 298 | if (loop.time() + 1.0) >= end_time: |
| 299 | break |
| 300 | await asyncio.sleep(1) |
| 301 | |
| 302 | asyncio.run(display_date()) |
| 303 | |
| 304 | |
| 305 | Running Tasks Concurrently |
| 306 | ========================== |
| 307 | |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame] | 308 | .. awaitablefunction:: gather(\*aws, loop=None, return_exceptions=False) |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 309 | |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame] | 310 | Run :ref:`awaitable objects <asyncio-awaitables>` in the *aws* |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 311 | sequence *concurrently*. |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 312 | |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame] | 313 | If any awaitable in *aws* is a coroutine, it is automatically |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 314 | scheduled as a Task. |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 315 | |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 316 | If all awaitables are completed successfully, the result is an |
| 317 | aggregate list of returned values. The order of result values |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame] | 318 | corresponds to the order of awaitables in *aws*. |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 319 | |
Yury Selivanov | db1a80e | 2018-09-21 16:23:15 -0400 | [diff] [blame] | 320 | If *return_exceptions* is ``False`` (default), the first |
| 321 | raised exception is immediately propagated to the task that |
| 322 | awaits on ``gather()``. Other awaitables in the *aws* sequence |
| 323 | **won't be cancelled** and will continue to run. |
| 324 | |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 325 | If *return_exceptions* is ``True``, exceptions are treated the |
| 326 | same as successful results, and aggregated in the result list. |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 327 | |
Yury Selivanov | db1a80e | 2018-09-21 16:23:15 -0400 | [diff] [blame] | 328 | If ``gather()`` is *cancelled*, all submitted awaitables |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 329 | (that have not completed yet) are also *cancelled*. |
| 330 | |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame] | 331 | If any Task or Future from the *aws* sequence is *cancelled*, it is |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 332 | treated as if it raised :exc:`CancelledError` -- the ``gather()`` |
| 333 | call is **not** cancelled in this case. This is to prevent the |
| 334 | cancellation of one submitted Task/Future to cause other |
| 335 | Tasks/Futures to be cancelled. |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 336 | |
Yury Selivanov | 7372c3b | 2018-09-14 15:11:24 -0700 | [diff] [blame] | 337 | .. _asyncio_example_gather: |
| 338 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 339 | Example:: |
| 340 | |
| 341 | import asyncio |
| 342 | |
| 343 | async def factorial(name, number): |
| 344 | f = 1 |
| 345 | for i in range(2, number + 1): |
| 346 | print(f"Task {name}: Compute factorial({i})...") |
| 347 | await asyncio.sleep(1) |
| 348 | f *= i |
| 349 | print(f"Task {name}: factorial({number}) = {f}") |
| 350 | |
| 351 | async def main(): |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 352 | # Schedule three calls *concurrently*: |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 353 | await asyncio.gather( |
| 354 | factorial("A", 2), |
| 355 | factorial("B", 3), |
| 356 | factorial("C", 4), |
Miguel Ángel García | 9c53fa6 | 2018-09-18 08:01:26 +0200 | [diff] [blame] | 357 | ) |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 358 | |
| 359 | asyncio.run(main()) |
| 360 | |
| 361 | # Expected output: |
| 362 | # |
| 363 | # Task A: Compute factorial(2)... |
| 364 | # Task B: Compute factorial(2)... |
| 365 | # Task C: Compute factorial(2)... |
| 366 | # Task A: factorial(2) = 2 |
| 367 | # Task B: Compute factorial(3)... |
| 368 | # Task C: Compute factorial(3)... |
| 369 | # Task B: factorial(3) = 6 |
| 370 | # Task C: Compute factorial(4)... |
| 371 | # Task C: factorial(4) = 24 |
| 372 | |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 373 | .. versionchanged:: 3.7 |
| 374 | If the *gather* itself is cancelled, the cancellation is |
| 375 | propagated regardless of *return_exceptions*. |
| 376 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 377 | |
Yury Selivanov | db1a80e | 2018-09-21 16:23:15 -0400 | [diff] [blame] | 378 | Shielding From Cancellation |
| 379 | =========================== |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 380 | |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame] | 381 | .. awaitablefunction:: shield(aw, \*, loop=None) |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 382 | |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 383 | Protect an :ref:`awaitable object <asyncio-awaitables>` |
| 384 | from being :meth:`cancelled <Task.cancel>`. |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 385 | |
Yury Selivanov | db1a80e | 2018-09-21 16:23:15 -0400 | [diff] [blame] | 386 | If *aw* is a coroutine it is automatically scheduled as a Task. |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 387 | |
| 388 | The statement:: |
| 389 | |
Andrew Svetlov | 8874342 | 2017-12-11 17:35:49 +0200 | [diff] [blame] | 390 | res = await shield(something()) |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 391 | |
Elvis Pranskevichus | 1fa2ec4 | 2018-09-17 19:16:44 -0400 | [diff] [blame] | 392 | is equivalent to:: |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 393 | |
Andrew Svetlov | 8874342 | 2017-12-11 17:35:49 +0200 | [diff] [blame] | 394 | res = await something() |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 395 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 396 | *except* that if the coroutine containing it is cancelled, the |
| 397 | Task running in ``something()`` is not cancelled. From the point |
| 398 | of view of ``something()``, the cancellation did not happen. |
| 399 | Although its caller is still cancelled, so the "await" expression |
Elvis Pranskevichus | 1fa2ec4 | 2018-09-17 19:16:44 -0400 | [diff] [blame] | 400 | still raises a :exc:`CancelledError`. |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 401 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 402 | If ``something()`` is cancelled by other means (i.e. from within |
| 403 | itself) that would also cancel ``shield()``. |
| 404 | |
| 405 | If it is desired to completely ignore cancellation (not recommended) |
| 406 | the ``shield()`` function should be combined with a try/except |
| 407 | clause, as follows:: |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 408 | |
| 409 | try: |
Andrew Svetlov | 8874342 | 2017-12-11 17:35:49 +0200 | [diff] [blame] | 410 | res = await shield(something()) |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 411 | except CancelledError: |
| 412 | res = None |
| 413 | |
Yury Selivanov | 950204d | 2016-05-16 16:23:00 -0400 | [diff] [blame] | 414 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 415 | Timeouts |
| 416 | ======== |
| 417 | |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame] | 418 | .. coroutinefunction:: wait_for(aw, timeout, \*, loop=None) |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 419 | |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame] | 420 | Wait for the *aw* :ref:`awaitable <asyncio-awaitables>` |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 421 | to complete with a timeout. |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 422 | |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame] | 423 | If *aw* is a coroutine it is automatically scheduled as a Task. |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 424 | |
| 425 | *timeout* can either be ``None`` or a float or int number of seconds |
| 426 | to wait for. If *timeout* is ``None``, block until the future |
| 427 | completes. |
| 428 | |
| 429 | If a timeout occurs, it cancels the task and raises |
| 430 | :exc:`asyncio.TimeoutError`. |
| 431 | |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 432 | To avoid the task :meth:`cancellation <Task.cancel>`, |
| 433 | wrap it in :func:`shield`. |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 434 | |
| 435 | The function will wait until the future is actually cancelled, |
| 436 | so the total wait time may exceed the *timeout*. |
| 437 | |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame] | 438 | If the wait is cancelled, the future *aw* is also cancelled. |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 439 | |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 440 | The *loop* argument is deprecated and scheduled for removal |
Yury Selivanov | fad6af2 | 2018-09-25 17:44:52 -0400 | [diff] [blame] | 441 | in Python 3.10. |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 442 | |
Yury Selivanov | 7372c3b | 2018-09-14 15:11:24 -0700 | [diff] [blame] | 443 | .. _asyncio_example_waitfor: |
| 444 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 445 | Example:: |
| 446 | |
| 447 | async def eternity(): |
| 448 | # Sleep for one hour |
| 449 | await asyncio.sleep(3600) |
| 450 | print('yay!') |
| 451 | |
| 452 | async def main(): |
| 453 | # Wait for at most 1 second |
| 454 | try: |
| 455 | await asyncio.wait_for(eternity(), timeout=1.0) |
| 456 | except asyncio.TimeoutError: |
| 457 | print('timeout!') |
| 458 | |
| 459 | asyncio.run(main()) |
| 460 | |
| 461 | # Expected output: |
| 462 | # |
| 463 | # timeout! |
| 464 | |
| 465 | .. versionchanged:: 3.7 |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame] | 466 | When *aw* is cancelled due to a timeout, ``wait_for`` waits |
| 467 | for *aw* to be cancelled. Previously, it raised |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 468 | :exc:`asyncio.TimeoutError` immediately. |
| 469 | |
| 470 | |
| 471 | Waiting Primitives |
| 472 | ================== |
| 473 | |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame] | 474 | .. coroutinefunction:: wait(aws, \*, loop=None, timeout=None,\ |
Andrew Svetlov | f124016 | 2016-01-11 14:40:35 +0200 | [diff] [blame] | 475 | return_when=ALL_COMPLETED) |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 476 | |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame] | 477 | Run :ref:`awaitable objects <asyncio-awaitables>` in the *aws* |
Yury Selivanov | 996859a | 2018-09-25 14:51:21 -0400 | [diff] [blame] | 478 | set concurrently and block until the condition specified |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 479 | by *return_when*. |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 480 | |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame] | 481 | If any awaitable in *aws* is a coroutine, it is automatically |
Yury Selivanov | 996859a | 2018-09-25 14:51:21 -0400 | [diff] [blame] | 482 | scheduled as a Task. Passing coroutines objects to |
| 483 | ``wait()`` directly is deprecated as it leads to |
| 484 | :ref:`confusing behavior <asyncio_example_wait_coroutine>`. |
Victor Stinner | db74d98 | 2014-06-10 11:16:05 +0200 | [diff] [blame] | 485 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 486 | Returns two sets of Tasks/Futures: ``(done, pending)``. |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 487 | |
Yury Selivanov | 996859a | 2018-09-25 14:51:21 -0400 | [diff] [blame] | 488 | Usage:: |
| 489 | |
| 490 | done, pending = await asyncio.wait(aws) |
| 491 | |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 492 | The *loop* argument is deprecated and scheduled for removal |
Yury Selivanov | fad6af2 | 2018-09-25 17:44:52 -0400 | [diff] [blame] | 493 | in Python 3.10. |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 494 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 495 | *timeout* (a float or int), if specified, can be used to control |
| 496 | the maximum number of seconds to wait before returning. |
| 497 | |
| 498 | Note that this function does not raise :exc:`asyncio.TimeoutError`. |
Elvis Pranskevichus | 1fa2ec4 | 2018-09-17 19:16:44 -0400 | [diff] [blame] | 499 | Futures or Tasks that aren't done when the timeout occurs are simply |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 500 | returned in the second set. |
| 501 | |
| 502 | *return_when* indicates when this function should return. It must |
| 503 | be one of the following constants: |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 504 | |
| 505 | .. tabularcolumns:: |l|L| |
| 506 | |
| 507 | +-----------------------------+----------------------------------------+ |
| 508 | | Constant | Description | |
| 509 | +=============================+========================================+ |
| 510 | | :const:`FIRST_COMPLETED` | The function will return when any | |
| 511 | | | future finishes or is cancelled. | |
| 512 | +-----------------------------+----------------------------------------+ |
| 513 | | :const:`FIRST_EXCEPTION` | The function will return when any | |
| 514 | | | future finishes by raising an | |
| 515 | | | exception. If no future raises an | |
| 516 | | | exception then it is equivalent to | |
| 517 | | | :const:`ALL_COMPLETED`. | |
| 518 | +-----------------------------+----------------------------------------+ |
| 519 | | :const:`ALL_COMPLETED` | The function will return when all | |
| 520 | | | futures finish or are cancelled. | |
| 521 | +-----------------------------+----------------------------------------+ |
| 522 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 523 | Unlike :func:`~asyncio.wait_for`, ``wait()`` does not cancel the |
| 524 | futures when a timeout occurs. |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 525 | |
Yury Selivanov | 996859a | 2018-09-25 14:51:21 -0400 | [diff] [blame] | 526 | .. _asyncio_example_wait_coroutine: |
| 527 | .. note:: |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 528 | |
Yury Selivanov | 996859a | 2018-09-25 14:51:21 -0400 | [diff] [blame] | 529 | ``wait()`` schedules coroutines as Tasks automatically and later |
| 530 | returns those implicitly created Task objects in ``(done, pending)`` |
| 531 | sets. Therefore the following code won't work as expected:: |
| 532 | |
| 533 | async def foo(): |
| 534 | return 42 |
| 535 | |
| 536 | coro = foo() |
| 537 | done, pending = await asyncio.wait({coro}) |
| 538 | |
| 539 | if coro in done: |
| 540 | # This branch will never be run! |
| 541 | |
| 542 | Here is how the above snippet can be fixed:: |
| 543 | |
| 544 | async def foo(): |
| 545 | return 42 |
| 546 | |
| 547 | task = asyncio.create_task(foo()) |
| 548 | done, pending = await asyncio.wait({task}) |
| 549 | |
| 550 | if task in done: |
| 551 | # Everything will work as expected now. |
| 552 | |
| 553 | Passing coroutine objects to ``wait()`` directly is |
| 554 | deprecated. |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 555 | |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 556 | |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame] | 557 | .. function:: as_completed(aws, \*, loop=None, timeout=None) |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 558 | |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame] | 559 | Run :ref:`awaitable objects <asyncio-awaitables>` in the *aws* |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 560 | set concurrently. Return an iterator of :class:`Future` objects. |
| 561 | Each Future object returned represents the earliest result |
| 562 | from the set of the remaining awaitables. |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 563 | |
| 564 | Raises :exc:`asyncio.TimeoutError` if the timeout occurs before |
| 565 | all Futures are done. |
| 566 | |
| 567 | Example:: |
| 568 | |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame] | 569 | for f in as_completed(aws): |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 570 | earliest_result = await f |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 571 | # ... |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 572 | |
Victor Stinner | 3e09e32 | 2013-12-03 01:22:06 +0100 | [diff] [blame] | 573 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 574 | Scheduling From Other Threads |
| 575 | ============================= |
Victor Stinner | 1ad5afc | 2014-01-30 00:18:50 +0100 | [diff] [blame] | 576 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 577 | .. function:: run_coroutine_threadsafe(coro, loop) |
Victor Stinner | 1ad5afc | 2014-01-30 00:18:50 +0100 | [diff] [blame] | 578 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 579 | Submit a coroutine to the given event loop. Thread-safe. |
Victor Stinner | 1ad5afc | 2014-01-30 00:18:50 +0100 | [diff] [blame] | 580 | |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 581 | Return a :class:`concurrent.futures.Future` to wait for the result |
| 582 | from another OS thread. |
Victor Stinner | 1ad5afc | 2014-01-30 00:18:50 +0100 | [diff] [blame] | 583 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 584 | This function is meant to be called from a different OS thread |
| 585 | than the one where the event loop is running. Example:: |
Victor Stinner | 72dcb0a | 2015-04-03 17:08:19 +0200 | [diff] [blame] | 586 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 587 | # Create a coroutine |
| 588 | coro = asyncio.sleep(1, result=3) |
Yury Selivanov | 37f15bc | 2014-02-20 16:20:44 -0500 | [diff] [blame] | 589 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 590 | # Submit the coroutine to a given loop |
| 591 | future = asyncio.run_coroutine_threadsafe(coro, loop) |
Victor Stinner | 1ad5afc | 2014-01-30 00:18:50 +0100 | [diff] [blame] | 592 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 593 | # Wait for the result with an optional timeout argument |
| 594 | assert future.result(timeout) == 3 |
| 595 | |
| 596 | If an exception is raised in the coroutine, the returned Future |
| 597 | will be notified. It can also be used to cancel the task in |
| 598 | the event loop:: |
| 599 | |
| 600 | try: |
| 601 | result = future.result(timeout) |
| 602 | except asyncio.TimeoutError: |
| 603 | print('The coroutine took too long, cancelling the task...') |
| 604 | future.cancel() |
| 605 | except Exception as exc: |
Mariatta | 9f43fbb | 2018-10-24 15:37:12 -0700 | [diff] [blame] | 606 | print(f'The coroutine raised an exception: {exc!r}') |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 607 | else: |
Mariatta | 9f43fbb | 2018-10-24 15:37:12 -0700 | [diff] [blame] | 608 | print(f'The coroutine returned: {result!r}') |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 609 | |
| 610 | See the :ref:`concurrency and multithreading <asyncio-multithreading>` |
| 611 | section of the documentation. |
| 612 | |
Vaibhav Gupta | 3a81076 | 2018-12-26 20:17:17 +0530 | [diff] [blame] | 613 | Unlike other asyncio functions this function requires the *loop* |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 614 | argument to be passed explicitly. |
| 615 | |
| 616 | .. versionadded:: 3.5.1 |
| 617 | |
| 618 | |
| 619 | Introspection |
| 620 | ============= |
| 621 | |
| 622 | |
| 623 | .. function:: current_task(loop=None) |
| 624 | |
| 625 | Return the currently running :class:`Task` instance, or ``None`` if |
| 626 | no task is running. |
| 627 | |
| 628 | If *loop* is ``None`` :func:`get_running_loop` is used to get |
| 629 | the current loop. |
| 630 | |
| 631 | .. versionadded:: 3.7 |
| 632 | |
| 633 | |
| 634 | .. function:: all_tasks(loop=None) |
| 635 | |
| 636 | Return a set of not yet finished :class:`Task` objects run by |
| 637 | the loop. |
| 638 | |
| 639 | If *loop* is ``None``, :func:`get_running_loop` is used for getting |
| 640 | current loop. |
| 641 | |
| 642 | .. versionadded:: 3.7 |
| 643 | |
| 644 | |
| 645 | Task Object |
| 646 | =========== |
| 647 | |
| 648 | .. class:: Task(coro, \*, loop=None, name=None) |
| 649 | |
Yury Selivanov | db1a80e | 2018-09-21 16:23:15 -0400 | [diff] [blame] | 650 | A :class:`Future-like <Future>` object that runs a Python |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 651 | :ref:`coroutine <coroutine>`. Not thread-safe. |
| 652 | |
| 653 | Tasks are used to run coroutines in event loops. |
| 654 | If a coroutine awaits on a Future, the Task suspends |
| 655 | the execution of the coroutine and waits for the completion |
| 656 | of the Future. When the Future is *done*, the execution of |
| 657 | the wrapped coroutine resumes. |
| 658 | |
| 659 | Event loops use cooperative scheduling: an event loop runs |
| 660 | one Task at a time. While a Task awaits for the completion of a |
| 661 | Future, the event loop runs other Tasks, callbacks, or performs |
| 662 | IO operations. |
| 663 | |
| 664 | Use the high-level :func:`asyncio.create_task` function to create |
Elvis Pranskevichus | 1fa2ec4 | 2018-09-17 19:16:44 -0400 | [diff] [blame] | 665 | Tasks, or the low-level :meth:`loop.create_task` or |
| 666 | :func:`ensure_future` functions. Manual instantiation of Tasks |
| 667 | is discouraged. |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 668 | |
| 669 | To cancel a running Task use the :meth:`cancel` method. Calling it |
| 670 | will cause the Task to throw a :exc:`CancelledError` exception into |
| 671 | the wrapped coroutine. If a coroutine is awaiting on a Future |
| 672 | object during cancellation, the Future object will be cancelled. |
| 673 | |
| 674 | :meth:`cancelled` can be used to check if the Task was cancelled. |
| 675 | The method returns ``True`` if the wrapped coroutine did not |
| 676 | suppress the :exc:`CancelledError` exception and was actually |
| 677 | cancelled. |
| 678 | |
| 679 | :class:`asyncio.Task` inherits from :class:`Future` all of its |
| 680 | APIs except :meth:`Future.set_result` and |
| 681 | :meth:`Future.set_exception`. |
| 682 | |
| 683 | Tasks support the :mod:`contextvars` module. When a Task |
| 684 | is created it copies the current context and later runs its |
| 685 | coroutine in the copied context. |
Elvis Pranskevichus | e2b340a | 2018-05-29 17:31:01 -0400 | [diff] [blame] | 686 | |
| 687 | .. versionchanged:: 3.7 |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 688 | Added support for the :mod:`contextvars` module. |
| 689 | |
| 690 | .. versionchanged:: 3.8 |
| 691 | Added the ``name`` parameter. |
| 692 | |
| 693 | .. method:: cancel() |
| 694 | |
| 695 | Request the Task to be cancelled. |
| 696 | |
| 697 | This arranges for a :exc:`CancelledError` exception to be thrown |
| 698 | into the wrapped coroutine on the next cycle of the event loop. |
| 699 | |
| 700 | The coroutine then has a chance to clean up or even deny the |
| 701 | request by suppressing the exception with a :keyword:`try` ... |
| 702 | ... ``except CancelledError`` ... :keyword:`finally` block. |
| 703 | Therefore, unlike :meth:`Future.cancel`, :meth:`Task.cancel` does |
| 704 | not guarantee that the Task will be cancelled, although |
| 705 | suppressing cancellation completely is not common and is actively |
| 706 | discouraged. |
| 707 | |
Yury Selivanov | 7372c3b | 2018-09-14 15:11:24 -0700 | [diff] [blame] | 708 | .. _asyncio_example_task_cancel: |
| 709 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 710 | The following example illustrates how coroutines can intercept |
| 711 | the cancellation request:: |
| 712 | |
| 713 | async def cancel_me(): |
| 714 | print('cancel_me(): before sleep') |
| 715 | |
| 716 | try: |
| 717 | # Wait for 1 hour |
| 718 | await asyncio.sleep(3600) |
| 719 | except asyncio.CancelledError: |
| 720 | print('cancel_me(): cancel sleep') |
| 721 | raise |
| 722 | finally: |
| 723 | print('cancel_me(): after sleep') |
| 724 | |
| 725 | async def main(): |
| 726 | # Create a "cancel_me" Task |
| 727 | task = asyncio.create_task(cancel_me()) |
| 728 | |
| 729 | # Wait for 1 second |
| 730 | await asyncio.sleep(1) |
| 731 | |
| 732 | task.cancel() |
| 733 | try: |
| 734 | await task |
| 735 | except asyncio.CancelledError: |
| 736 | print("main(): cancel_me is cancelled now") |
| 737 | |
| 738 | asyncio.run(main()) |
| 739 | |
| 740 | # Expected output: |
| 741 | # |
| 742 | # cancel_me(): before sleep |
| 743 | # cancel_me(): cancel sleep |
| 744 | # cancel_me(): after sleep |
| 745 | # main(): cancel_me is cancelled now |
| 746 | |
| 747 | .. method:: cancelled() |
| 748 | |
| 749 | Return ``True`` if the Task is *cancelled*. |
| 750 | |
| 751 | The Task is *cancelled* when the cancellation was requested with |
| 752 | :meth:`cancel` and the wrapped coroutine propagated the |
| 753 | :exc:`CancelledError` exception thrown into it. |
| 754 | |
| 755 | .. method:: done() |
| 756 | |
| 757 | Return ``True`` if the Task is *done*. |
| 758 | |
| 759 | A Task is *done* when the wrapped coroutine either returned |
| 760 | a value, raised an exception, or the Task was cancelled. |
| 761 | |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame] | 762 | .. method:: result() |
| 763 | |
| 764 | Return the result of the Task. |
| 765 | |
| 766 | If the Task is *done*, the result of the wrapped coroutine |
| 767 | is returned (or if the coroutine raised an exception, that |
| 768 | exception is re-raised.) |
| 769 | |
| 770 | If the Task has been *cancelled*, this method raises |
| 771 | a :exc:`CancelledError` exception. |
| 772 | |
| 773 | If the Task's result isn't yet available, this method raises |
| 774 | a :exc:`InvalidStateError` exception. |
| 775 | |
| 776 | .. method:: exception() |
| 777 | |
| 778 | Return the exception of the Task. |
| 779 | |
| 780 | If the wrapped coroutine raised an exception that exception |
| 781 | is returned. If the wrapped coroutine returned normally |
| 782 | this method returns ``None``. |
| 783 | |
| 784 | If the Task has been *cancelled*, this method raises a |
| 785 | :exc:`CancelledError` exception. |
| 786 | |
| 787 | If the Task isn't *done* yet, this method raises an |
| 788 | :exc:`InvalidStateError` exception. |
| 789 | |
| 790 | .. method:: add_done_callback(callback, *, context=None) |
| 791 | |
| 792 | Add a callback to be run when the Task is *done*. |
| 793 | |
| 794 | This method should only be used in low-level callback-based code. |
| 795 | |
| 796 | See the documentation of :meth:`Future.add_done_callback` |
| 797 | for more details. |
| 798 | |
| 799 | .. method:: remove_done_callback(callback) |
| 800 | |
| 801 | Remove *callback* from the callbacks list. |
| 802 | |
| 803 | This method should only be used in low-level callback-based code. |
| 804 | |
| 805 | See the documentation of :meth:`Future.remove_done_callback` |
| 806 | for more details. |
| 807 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 808 | .. method:: get_stack(\*, limit=None) |
| 809 | |
| 810 | Return the list of stack frames for this Task. |
| 811 | |
| 812 | If the wrapped coroutine is not done, this returns the stack |
| 813 | where it is suspended. If the coroutine has completed |
| 814 | successfully or was cancelled, this returns an empty list. |
| 815 | If the coroutine was terminated by an exception, this returns |
| 816 | the list of traceback frames. |
| 817 | |
| 818 | The frames are always ordered from oldest to newest. |
| 819 | |
| 820 | Only one stack frame is returned for a suspended coroutine. |
| 821 | |
| 822 | The optional *limit* argument sets the maximum number of frames |
| 823 | to return; by default all available frames are returned. |
| 824 | The ordering of the returned list differs depending on whether |
| 825 | a stack or a traceback is returned: the newest frames of a |
| 826 | stack are returned, but the oldest frames of a traceback are |
| 827 | returned. (This matches the behavior of the traceback module.) |
| 828 | |
| 829 | .. method:: print_stack(\*, limit=None, file=None) |
| 830 | |
| 831 | Print the stack or traceback for this Task. |
| 832 | |
| 833 | This produces output similar to that of the traceback module |
| 834 | for the frames retrieved by :meth:`get_stack`. |
| 835 | |
| 836 | The *limit* argument is passed to :meth:`get_stack` directly. |
| 837 | |
| 838 | The *file* argument is an I/O stream to which the output |
| 839 | is written; by default output is written to :data:`sys.stderr`. |
| 840 | |
| 841 | .. method:: get_name() |
| 842 | |
| 843 | Return the name of the Task. |
| 844 | |
| 845 | If no name has been explicitly assigned to the Task, the default |
| 846 | asyncio Task implementation generates a default name during |
| 847 | instantiation. |
| 848 | |
| 849 | .. versionadded:: 3.8 |
| 850 | |
| 851 | .. method:: set_name(value) |
| 852 | |
| 853 | Set the name of the Task. |
| 854 | |
| 855 | The *value* argument can be any object, which is then |
| 856 | converted to a string. |
| 857 | |
| 858 | In the default Task implementation, the name will be visible |
| 859 | in the :func:`repr` output of a task object. |
| 860 | |
| 861 | .. versionadded:: 3.8 |
| 862 | |
| 863 | .. classmethod:: all_tasks(loop=None) |
| 864 | |
| 865 | Return a set of all tasks for an event loop. |
| 866 | |
| 867 | By default all tasks for the current event loop are returned. |
| 868 | If *loop* is ``None``, the :func:`get_event_loop` function |
| 869 | is used to get the current loop. |
| 870 | |
Elvis Pranskevichus | 1fa2ec4 | 2018-09-17 19:16:44 -0400 | [diff] [blame] | 871 | This method is **deprecated** and will be removed in |
Yury Selivanov | db1a80e | 2018-09-21 16:23:15 -0400 | [diff] [blame] | 872 | Python 3.9. Use the :func:`asyncio.all_tasks` function instead. |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 873 | |
| 874 | .. classmethod:: current_task(loop=None) |
| 875 | |
| 876 | Return the currently running task or ``None``. |
| 877 | |
| 878 | If *loop* is ``None``, the :func:`get_event_loop` function |
| 879 | is used to get the current loop. |
| 880 | |
Elvis Pranskevichus | 1fa2ec4 | 2018-09-17 19:16:44 -0400 | [diff] [blame] | 881 | This method is **deprecated** and will be removed in |
Yury Selivanov | db1a80e | 2018-09-21 16:23:15 -0400 | [diff] [blame] | 882 | Python 3.9. Use the :func:`asyncio.current_task` function |
| 883 | instead. |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 884 | |
| 885 | |
| 886 | .. _asyncio_generator_based_coro: |
| 887 | |
| 888 | Generator-based Coroutines |
| 889 | ========================== |
| 890 | |
| 891 | .. note:: |
| 892 | |
| 893 | Support for generator-based coroutines is **deprecated** and |
Yury Selivanov | fad6af2 | 2018-09-25 17:44:52 -0400 | [diff] [blame] | 894 | is scheduled for removal in Python 3.10. |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 895 | |
| 896 | Generator-based coroutines predate async/await syntax. They are |
Elvis Pranskevichus | 1fa2ec4 | 2018-09-17 19:16:44 -0400 | [diff] [blame] | 897 | Python generators that use ``yield from`` expressions to await |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 898 | on Futures and other coroutines. |
| 899 | |
| 900 | Generator-based coroutines should be decorated with |
| 901 | :func:`@asyncio.coroutine <asyncio.coroutine>`, although this is not |
| 902 | enforced. |
| 903 | |
| 904 | |
| 905 | .. decorator:: coroutine |
| 906 | |
| 907 | Decorator to mark generator-based coroutines. |
| 908 | |
| 909 | This decorator enables legacy generator-based coroutines to be |
| 910 | compatible with async/await code:: |
| 911 | |
| 912 | @asyncio.coroutine |
| 913 | def old_style_coroutine(): |
| 914 | yield from asyncio.sleep(1) |
| 915 | |
| 916 | async def main(): |
| 917 | await old_style_coroutine() |
| 918 | |
| 919 | This decorator is **deprecated** and is scheduled for removal in |
Yury Selivanov | fad6af2 | 2018-09-25 17:44:52 -0400 | [diff] [blame] | 920 | Python 3.10. |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 921 | |
| 922 | This decorator should not be used for :keyword:`async def` |
| 923 | coroutines. |
| 924 | |
| 925 | .. function:: iscoroutine(obj) |
| 926 | |
| 927 | Return ``True`` if *obj* is a :ref:`coroutine object <coroutine>`. |
| 928 | |
| 929 | This method is different from :func:`inspect.iscoroutine` because |
Yury Selivanov | 59ee5b1 | 2018-09-27 15:48:30 -0400 | [diff] [blame] | 930 | it returns ``True`` for generator-based coroutines. |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 931 | |
| 932 | .. function:: iscoroutinefunction(func) |
| 933 | |
| 934 | Return ``True`` if *func* is a :ref:`coroutine function |
| 935 | <coroutine>`. |
| 936 | |
| 937 | This method is different from :func:`inspect.iscoroutinefunction` |
| 938 | because it returns ``True`` for generator-based coroutine functions |
| 939 | decorated with :func:`@coroutine <coroutine>`. |