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