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(): |
| 60 | print('started at', time.strftime('%X')) |
| 61 | |
| 62 | await say_after(1, 'hello') |
| 63 | await say_after(2, 'world') |
| 64 | |
| 65 | print('finished at', time.strftime('%X')) |
| 66 | |
| 67 | asyncio.run(main()) |
| 68 | |
| 69 | Expected output:: |
| 70 | |
| 71 | started at 17:13:52 |
| 72 | hello |
| 73 | world |
| 74 | finished at 17:13:55 |
| 75 | |
Elvis 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 | |
| 89 | print('started at', time.strftime('%X')) |
| 90 | |
| 91 | # Wait until both tasks are completed (should take |
| 92 | # around 2 seconds.) |
| 93 | await task1 |
| 94 | await task2 |
| 95 | |
| 96 | print('finished at', time.strftime('%X')) |
| 97 | |
| 98 | Note that expected output now shows that the snippet runs |
| 99 | 1 second faster than before:: |
| 100 | |
| 101 | started at 17:14:32 |
| 102 | hello |
| 103 | world |
| 104 | finished at 17:14:34 |
| 105 | |
Yury 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()". |
| 132 | # (a coroutine object is created but not awaited) |
| 133 | nested() |
| 134 | |
| 135 | # Let's do it differently now and await it: |
| 136 | print(await nested()) # will print "42". |
| 137 | |
| 138 | asyncio.run(main()) |
| 139 | |
| 140 | .. important:: |
| 141 | |
| 142 | In this documentation the term "coroutine" can be used for |
| 143 | two closely related concepts: |
| 144 | |
| 145 | * a *coroutine function*: an :keyword:`async def` function; |
| 146 | |
| 147 | * a *coroutine object*: an object returned by calling a |
| 148 | *coroutine function*. |
| 149 | |
| 150 | asyncio also supports legacy :ref:`generator-based |
| 151 | <asyncio_generator_based_coro>` coroutines. |
| 152 | |
| 153 | |
| 154 | .. rubric:: Tasks |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 155 | |
| 156 | *Tasks* are used to schedule coroutines *concurrently*. |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 157 | |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame^] | 158 | When a coroutine is wrapped into a *Task* with functions like |
| 159 | :func:`asyncio.create_task` the coroutine is automatically |
| 160 | scheduled to run soon:: |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 161 | |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame^] | 162 | import asyncio |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 163 | |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame^] | 164 | async def nested(): |
| 165 | return 42 |
| 166 | |
| 167 | async def main(): |
| 168 | # Schedule nested() to run soon concurrently |
| 169 | # with "main()". |
| 170 | task = asyncio.create_task(nested()) |
| 171 | |
| 172 | # "task" can now be used to cancel "nested()", or |
| 173 | # can simply be awaited to wait until it is complete: |
| 174 | await task |
| 175 | |
| 176 | asyncio.run(main()) |
Victor Stinner | 337e03f | 2014-08-11 01:11:13 +0200 | [diff] [blame] | 177 | |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 178 | |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 179 | .. rubric:: Futures |
| 180 | |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame^] | 181 | A :class:`Future` is a special **low-level** awaitable object that |
| 182 | represents an **eventual result** of an asynchronous operation. |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 183 | |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame^] | 184 | When a Future object is *awaited* it means that the coroutine will |
| 185 | wait until the Future is resolved in some other place. |
| 186 | |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 187 | Future objects in asyncio are needed to allow callback-based code |
| 188 | to be used with async/await. |
| 189 | |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame^] | 190 | Normally **there is no need** to create Future objects at the |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 191 | application level code. |
| 192 | |
| 193 | Future objects, sometimes exposed by libraries and some asyncio |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame^] | 194 | APIs, can be awaited:: |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 195 | |
| 196 | async def main(): |
| 197 | await function_that_returns_a_future_object() |
| 198 | |
| 199 | # this is also valid: |
| 200 | await asyncio.gather( |
| 201 | function_that_returns_a_future_object(), |
| 202 | some_python_coroutine() |
| 203 | ) |
| 204 | |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame^] | 205 | A good example of a low-level function that returns a Future object |
| 206 | is :meth:`loop.run_in_executor`. |
| 207 | |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 208 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 209 | Running an asyncio Program |
| 210 | ========================== |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 211 | |
Elvis Pranskevichus | 63536bd | 2018-05-19 23:15:06 -0400 | [diff] [blame] | 212 | .. function:: run(coro, \*, debug=False) |
Yury Selivanov | 02a0a19 | 2017-12-14 09:42:21 -0500 | [diff] [blame] | 213 | |
| 214 | This function runs the passed coroutine, taking care of |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 215 | managing the asyncio event loop and *finalizing asynchronous |
| 216 | generators*. |
Yury Selivanov | 02a0a19 | 2017-12-14 09:42:21 -0500 | [diff] [blame] | 217 | |
| 218 | This function cannot be called when another asyncio event loop is |
| 219 | running in the same thread. |
| 220 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 221 | 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] | 222 | |
| 223 | This function always creates a new event loop and closes it at |
| 224 | the end. It should be used as a main entry point for asyncio |
| 225 | programs, and should ideally only be called once. |
| 226 | |
| 227 | .. versionadded:: 3.7 |
Elvis Pranskevichus | 1fa2ec4 | 2018-09-17 19:16:44 -0400 | [diff] [blame] | 228 | **Important:** this function has been added to asyncio in |
| 229 | Python 3.7 on a :term:`provisional basis <provisional api>`. |
Yury Selivanov | 02a0a19 | 2017-12-14 09:42:21 -0500 | [diff] [blame] | 230 | |
| 231 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 232 | Creating Tasks |
| 233 | ============== |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 234 | |
Alex Grönholm | cca4eec | 2018-08-09 00:06:47 +0300 | [diff] [blame] | 235 | .. function:: create_task(coro, \*, name=None) |
Andrew Svetlov | f74ef45 | 2017-12-15 07:04:38 +0200 | [diff] [blame] | 236 | |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame^] | 237 | Wrap the *coro* :ref:`coroutine <coroutine>` into a :class:`Task` |
| 238 | and schedule its execution. Return the Task object. |
Alex Grönholm | cca4eec | 2018-08-09 00:06:47 +0300 | [diff] [blame] | 239 | |
| 240 | If *name* is not ``None``, it is set as the name of the task using |
| 241 | :meth:`Task.set_name`. |
Andrew Svetlov | f74ef45 | 2017-12-15 07:04:38 +0200 | [diff] [blame] | 242 | |
Elvis Pranskevichus | 1fa2ec4 | 2018-09-17 19:16:44 -0400 | [diff] [blame] | 243 | 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] | 244 | :exc:`RuntimeError` is raised if there is no running loop in |
| 245 | current thread. |
| 246 | |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 247 | This function has been **added in Python 3.7**. Prior to |
| 248 | Python 3.7, the low-level :func:`asyncio.ensure_future` function |
| 249 | can be used instead:: |
| 250 | |
| 251 | async def coro(): |
| 252 | ... |
| 253 | |
| 254 | # In Python 3.7+ |
| 255 | task = asyncio.create_task(coro()) |
| 256 | ... |
| 257 | |
| 258 | # This works in all Python versions but is less readable |
| 259 | task = asyncio.ensure_future(coro()) |
| 260 | ... |
| 261 | |
Andrew Svetlov | f74ef45 | 2017-12-15 07:04:38 +0200 | [diff] [blame] | 262 | .. versionadded:: 3.7 |
| 263 | |
Alex Grönholm | cca4eec | 2018-08-09 00:06:47 +0300 | [diff] [blame] | 264 | .. versionchanged:: 3.8 |
| 265 | Added the ``name`` parameter. |
| 266 | |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 267 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 268 | Sleeping |
| 269 | ======== |
Andrew Svetlov | f124016 | 2016-01-11 14:40:35 +0200 | [diff] [blame] | 270 | |
Victor Stinner | bdd574d | 2015-02-12 22:49:18 +0100 | [diff] [blame] | 271 | .. coroutinefunction:: sleep(delay, result=None, \*, loop=None) |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 272 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 273 | Block for *delay* seconds. |
| 274 | |
| 275 | If *result* is provided, it is returned to the caller |
Eli Bendersky | 2d26af8 | 2014-01-20 06:59:23 -0800 | [diff] [blame] | 276 | when the coroutine completes. |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 277 | |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 278 | The *loop* argument is deprecated and scheduled for removal |
| 279 | in Python 4.0. |
| 280 | |
Yury Selivanov | 7372c3b | 2018-09-14 15:11:24 -0700 | [diff] [blame] | 281 | .. _asyncio_example_sleep: |
Victor Stinner | 45b27ed | 2014-02-01 02:36:43 +0100 | [diff] [blame] | 282 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 283 | Example of coroutine displaying the current date every second |
Elvis Pranskevichus | 1fa2ec4 | 2018-09-17 19:16:44 -0400 | [diff] [blame] | 284 | for 5 seconds:: |
Victor Stinner | bdd574d | 2015-02-12 22:49:18 +0100 | [diff] [blame] | 285 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 286 | import asyncio |
| 287 | import datetime |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 288 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 289 | async def display_date(): |
| 290 | loop = asyncio.get_running_loop() |
| 291 | end_time = loop.time() + 5.0 |
| 292 | while True: |
| 293 | print(datetime.datetime.now()) |
| 294 | if (loop.time() + 1.0) >= end_time: |
| 295 | break |
| 296 | await asyncio.sleep(1) |
| 297 | |
| 298 | asyncio.run(display_date()) |
| 299 | |
| 300 | |
| 301 | Running Tasks Concurrently |
| 302 | ========================== |
| 303 | |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame^] | 304 | .. awaitablefunction:: gather(\*aws, loop=None, return_exceptions=False) |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 305 | |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame^] | 306 | Run :ref:`awaitable objects <asyncio-awaitables>` in the *aws* |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 307 | sequence *concurrently*. |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 308 | |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame^] | 309 | If any awaitable in *aws* is a coroutine, it is automatically |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 310 | scheduled as a Task. |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 311 | |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 312 | If all awaitables are completed successfully, the result is an |
| 313 | aggregate list of returned values. The order of result values |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame^] | 314 | corresponds to the order of awaitables in *aws*. |
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 *return_exceptions* is ``True``, exceptions are treated the |
| 317 | same as successful results, and aggregated in the result list. |
| 318 | Otherwise, the first raised exception is immediately propagated |
| 319 | to the task that awaits on ``gather()``. |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 320 | |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 321 | If ``gather`` is *cancelled*, all submitted awaitables |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 322 | (that have not completed yet) are also *cancelled*. |
| 323 | |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame^] | 324 | 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] | 325 | treated as if it raised :exc:`CancelledError` -- the ``gather()`` |
| 326 | call is **not** cancelled in this case. This is to prevent the |
| 327 | cancellation of one submitted Task/Future to cause other |
| 328 | Tasks/Futures to be cancelled. |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 329 | |
Yury Selivanov | 7372c3b | 2018-09-14 15:11:24 -0700 | [diff] [blame] | 330 | .. _asyncio_example_gather: |
| 331 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 332 | Example:: |
| 333 | |
| 334 | import asyncio |
| 335 | |
| 336 | async def factorial(name, number): |
| 337 | f = 1 |
| 338 | for i in range(2, number + 1): |
| 339 | print(f"Task {name}: Compute factorial({i})...") |
| 340 | await asyncio.sleep(1) |
| 341 | f *= i |
| 342 | print(f"Task {name}: factorial({number}) = {f}") |
| 343 | |
| 344 | async def main(): |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 345 | # Schedule three calls *concurrently*: |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 346 | await asyncio.gather( |
| 347 | factorial("A", 2), |
| 348 | factorial("B", 3), |
| 349 | factorial("C", 4), |
Miguel Ángel García | 9c53fa6 | 2018-09-18 08:01:26 +0200 | [diff] [blame] | 350 | ) |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 351 | |
| 352 | asyncio.run(main()) |
| 353 | |
| 354 | # Expected output: |
| 355 | # |
| 356 | # Task A: Compute factorial(2)... |
| 357 | # Task B: Compute factorial(2)... |
| 358 | # Task C: Compute factorial(2)... |
| 359 | # Task A: factorial(2) = 2 |
| 360 | # Task B: Compute factorial(3)... |
| 361 | # Task C: Compute factorial(3)... |
| 362 | # Task B: factorial(3) = 6 |
| 363 | # Task C: Compute factorial(4)... |
| 364 | # Task C: factorial(4) = 24 |
| 365 | |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 366 | .. versionchanged:: 3.7 |
| 367 | If the *gather* itself is cancelled, the cancellation is |
| 368 | propagated regardless of *return_exceptions*. |
| 369 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 370 | |
| 371 | Shielding Tasks From Cancellation |
| 372 | ================================= |
| 373 | |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame^] | 374 | .. awaitablefunction:: shield(aw, \*, loop=None) |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 375 | |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 376 | Protect an :ref:`awaitable object <asyncio-awaitables>` |
| 377 | from being :meth:`cancelled <Task.cancel>`. |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 378 | |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame^] | 379 | *aw* can be a coroutine, a Task, or a Future-like object. If |
| 380 | *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 | |
Elvis Pranskevichus | 1fa2ec4 | 2018-09-17 19:16:44 -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 | 3faaa88 | 2018-09-14 13:32:07 -0700 | [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 |
Elvis Pranskevichus | 1fa2ec4 | 2018-09-17 19:16:44 -0400 | [diff] [blame] | 394 | still raises a :exc:`CancelledError`. |
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 | 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 | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 409 | Timeouts |
| 410 | ======== |
| 411 | |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame^] | 412 | .. coroutinefunction:: wait_for(aw, timeout, \*, loop=None) |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 413 | |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame^] | 414 | Wait for the *aw* :ref:`awaitable <asyncio-awaitables>` |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 415 | to complete with a timeout. |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 416 | |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame^] | 417 | If *aw* is a coroutine it is automatically scheduled as a Task. |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [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 | |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 426 | To avoid the task :meth:`cancellation <Task.cancel>`, |
| 427 | wrap it in :func:`shield`. |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [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 | |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame^] | 432 | If the wait is cancelled, the future *aw* is also cancelled. |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 433 | |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 434 | The *loop* argument is deprecated and scheduled for removal |
| 435 | in Python 4.0. |
| 436 | |
Yury Selivanov | 7372c3b | 2018-09-14 15:11:24 -0700 | [diff] [blame] | 437 | .. _asyncio_example_waitfor: |
| 438 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 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 |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [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 | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 462 | :exc:`asyncio.TimeoutError` immediately. |
| 463 | |
| 464 | |
| 465 | Waiting Primitives |
| 466 | ================== |
| 467 | |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [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 | |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame^] | 471 | Run :ref:`awaitable objects <asyncio-awaitables>` in the *aws* |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 472 | sequence concurrently and block until the condition specified |
| 473 | by *return_when*. |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 474 | |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame^] | 475 | If any awaitable in *aws* is a coroutine, it is automatically |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 476 | scheduled as a Task. |
Victor Stinner | db74d98 | 2014-06-10 11:16:05 +0200 | [diff] [blame] | 477 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 478 | Returns two sets of Tasks/Futures: ``(done, pending)``. |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 479 | |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 480 | The *loop* argument is deprecated and scheduled for removal |
| 481 | in Python 4.0. |
| 482 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 483 | *timeout* (a float or int), if specified, can be used to control |
| 484 | the maximum number of seconds to wait before returning. |
| 485 | |
| 486 | Note that this function does not raise :exc:`asyncio.TimeoutError`. |
Elvis Pranskevichus | 1fa2ec4 | 2018-09-17 19:16:44 -0400 | [diff] [blame] | 487 | 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] | 488 | returned in the second set. |
| 489 | |
| 490 | *return_when* indicates when this function should return. It must |
| 491 | be one of the following constants: |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 492 | |
| 493 | .. tabularcolumns:: |l|L| |
| 494 | |
| 495 | +-----------------------------+----------------------------------------+ |
| 496 | | Constant | Description | |
| 497 | +=============================+========================================+ |
| 498 | | :const:`FIRST_COMPLETED` | The function will return when any | |
| 499 | | | future finishes or is cancelled. | |
| 500 | +-----------------------------+----------------------------------------+ |
| 501 | | :const:`FIRST_EXCEPTION` | The function will return when any | |
| 502 | | | future finishes by raising an | |
| 503 | | | exception. If no future raises an | |
| 504 | | | exception then it is equivalent to | |
| 505 | | | :const:`ALL_COMPLETED`. | |
| 506 | +-----------------------------+----------------------------------------+ |
| 507 | | :const:`ALL_COMPLETED` | The function will return when all | |
| 508 | | | futures finish or are cancelled. | |
| 509 | +-----------------------------+----------------------------------------+ |
| 510 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 511 | Unlike :func:`~asyncio.wait_for`, ``wait()`` does not cancel the |
| 512 | futures when a timeout occurs. |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 513 | |
| 514 | Usage:: |
| 515 | |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame^] | 516 | done, pending = await asyncio.wait(aws) |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 517 | |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 518 | |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame^] | 519 | .. function:: as_completed(aws, \*, loop=None, timeout=None) |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 520 | |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame^] | 521 | Run :ref:`awaitable objects <asyncio-awaitables>` in the *aws* |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 522 | set concurrently. Return an iterator of :class:`Future` objects. |
| 523 | Each Future object returned represents the earliest result |
| 524 | from the set of the remaining awaitables. |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 525 | |
| 526 | Raises :exc:`asyncio.TimeoutError` if the timeout occurs before |
| 527 | all Futures are done. |
| 528 | |
| 529 | Example:: |
| 530 | |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame^] | 531 | for f in as_completed(aws): |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 532 | earliest_result = await f |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 533 | # ... |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 534 | |
Victor Stinner | 3e09e32 | 2013-12-03 01:22:06 +0100 | [diff] [blame] | 535 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 536 | Scheduling From Other Threads |
| 537 | ============================= |
Victor Stinner | 1ad5afc | 2014-01-30 00:18:50 +0100 | [diff] [blame] | 538 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 539 | .. function:: run_coroutine_threadsafe(coro, loop) |
Victor Stinner | 1ad5afc | 2014-01-30 00:18:50 +0100 | [diff] [blame] | 540 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 541 | Submit a coroutine to the given event loop. Thread-safe. |
Victor Stinner | 1ad5afc | 2014-01-30 00:18:50 +0100 | [diff] [blame] | 542 | |
Yury Selivanov | 4715039 | 2018-09-18 17:55:44 -0400 | [diff] [blame] | 543 | Return a :class:`concurrent.futures.Future` to wait for the result |
| 544 | from another OS thread. |
Victor Stinner | 1ad5afc | 2014-01-30 00:18:50 +0100 | [diff] [blame] | 545 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 546 | This function is meant to be called from a different OS thread |
| 547 | than the one where the event loop is running. Example:: |
Victor Stinner | 72dcb0a | 2015-04-03 17:08:19 +0200 | [diff] [blame] | 548 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 549 | # Create a coroutine |
| 550 | coro = asyncio.sleep(1, result=3) |
Yury Selivanov | 37f15bc | 2014-02-20 16:20:44 -0500 | [diff] [blame] | 551 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 552 | # Submit the coroutine to a given loop |
| 553 | future = asyncio.run_coroutine_threadsafe(coro, loop) |
Victor Stinner | 1ad5afc | 2014-01-30 00:18:50 +0100 | [diff] [blame] | 554 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 555 | # Wait for the result with an optional timeout argument |
| 556 | assert future.result(timeout) == 3 |
| 557 | |
| 558 | If an exception is raised in the coroutine, the returned Future |
| 559 | will be notified. It can also be used to cancel the task in |
| 560 | the event loop:: |
| 561 | |
| 562 | try: |
| 563 | result = future.result(timeout) |
| 564 | except asyncio.TimeoutError: |
| 565 | print('The coroutine took too long, cancelling the task...') |
| 566 | future.cancel() |
| 567 | except Exception as exc: |
| 568 | print('The coroutine raised an exception: {!r}'.format(exc)) |
| 569 | else: |
| 570 | print('The coroutine returned: {!r}'.format(result)) |
| 571 | |
| 572 | See the :ref:`concurrency and multithreading <asyncio-multithreading>` |
| 573 | section of the documentation. |
| 574 | |
| 575 | Unlike other asyncio functions this functions requires the *loop* |
| 576 | argument to be passed explicitly. |
| 577 | |
| 578 | .. versionadded:: 3.5.1 |
| 579 | |
| 580 | |
| 581 | Introspection |
| 582 | ============= |
| 583 | |
| 584 | |
| 585 | .. function:: current_task(loop=None) |
| 586 | |
| 587 | Return the currently running :class:`Task` instance, or ``None`` if |
| 588 | no task is running. |
| 589 | |
| 590 | If *loop* is ``None`` :func:`get_running_loop` is used to get |
| 591 | the current loop. |
| 592 | |
| 593 | .. versionadded:: 3.7 |
| 594 | |
| 595 | |
| 596 | .. function:: all_tasks(loop=None) |
| 597 | |
| 598 | Return a set of not yet finished :class:`Task` objects run by |
| 599 | the loop. |
| 600 | |
| 601 | If *loop* is ``None``, :func:`get_running_loop` is used for getting |
| 602 | current loop. |
| 603 | |
| 604 | .. versionadded:: 3.7 |
| 605 | |
| 606 | |
| 607 | Task Object |
| 608 | =========== |
| 609 | |
| 610 | .. class:: Task(coro, \*, loop=None, name=None) |
| 611 | |
| 612 | A :class:`Future`-like object that wraps a Python |
| 613 | :ref:`coroutine <coroutine>`. Not thread-safe. |
| 614 | |
| 615 | Tasks are used to run coroutines in event loops. |
| 616 | If a coroutine awaits on a Future, the Task suspends |
| 617 | the execution of the coroutine and waits for the completion |
| 618 | of the Future. When the Future is *done*, the execution of |
| 619 | the wrapped coroutine resumes. |
| 620 | |
| 621 | Event loops use cooperative scheduling: an event loop runs |
| 622 | one Task at a time. While a Task awaits for the completion of a |
| 623 | Future, the event loop runs other Tasks, callbacks, or performs |
| 624 | IO operations. |
| 625 | |
| 626 | Use the high-level :func:`asyncio.create_task` function to create |
Elvis Pranskevichus | 1fa2ec4 | 2018-09-17 19:16:44 -0400 | [diff] [blame] | 627 | Tasks, or the low-level :meth:`loop.create_task` or |
| 628 | :func:`ensure_future` functions. Manual instantiation of Tasks |
| 629 | is discouraged. |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 630 | |
| 631 | To cancel a running Task use the :meth:`cancel` method. Calling it |
| 632 | will cause the Task to throw a :exc:`CancelledError` exception into |
| 633 | the wrapped coroutine. If a coroutine is awaiting on a Future |
| 634 | object during cancellation, the Future object will be cancelled. |
| 635 | |
| 636 | :meth:`cancelled` can be used to check if the Task was cancelled. |
| 637 | The method returns ``True`` if the wrapped coroutine did not |
| 638 | suppress the :exc:`CancelledError` exception and was actually |
| 639 | cancelled. |
| 640 | |
| 641 | :class:`asyncio.Task` inherits from :class:`Future` all of its |
| 642 | APIs except :meth:`Future.set_result` and |
| 643 | :meth:`Future.set_exception`. |
| 644 | |
| 645 | Tasks support the :mod:`contextvars` module. When a Task |
| 646 | is created it copies the current context and later runs its |
| 647 | coroutine in the copied context. |
Elvis Pranskevichus | e2b340a | 2018-05-29 17:31:01 -0400 | [diff] [blame] | 648 | |
| 649 | .. versionchanged:: 3.7 |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 650 | Added support for the :mod:`contextvars` module. |
| 651 | |
| 652 | .. versionchanged:: 3.8 |
| 653 | Added the ``name`` parameter. |
| 654 | |
| 655 | .. method:: cancel() |
| 656 | |
| 657 | Request the Task to be cancelled. |
| 658 | |
| 659 | This arranges for a :exc:`CancelledError` exception to be thrown |
| 660 | into the wrapped coroutine on the next cycle of the event loop. |
| 661 | |
| 662 | The coroutine then has a chance to clean up or even deny the |
| 663 | request by suppressing the exception with a :keyword:`try` ... |
| 664 | ... ``except CancelledError`` ... :keyword:`finally` block. |
| 665 | Therefore, unlike :meth:`Future.cancel`, :meth:`Task.cancel` does |
| 666 | not guarantee that the Task will be cancelled, although |
| 667 | suppressing cancellation completely is not common and is actively |
| 668 | discouraged. |
| 669 | |
Yury Selivanov | 7372c3b | 2018-09-14 15:11:24 -0700 | [diff] [blame] | 670 | .. _asyncio_example_task_cancel: |
| 671 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 672 | The following example illustrates how coroutines can intercept |
| 673 | the cancellation request:: |
| 674 | |
| 675 | async def cancel_me(): |
| 676 | print('cancel_me(): before sleep') |
| 677 | |
| 678 | try: |
| 679 | # Wait for 1 hour |
| 680 | await asyncio.sleep(3600) |
| 681 | except asyncio.CancelledError: |
| 682 | print('cancel_me(): cancel sleep') |
| 683 | raise |
| 684 | finally: |
| 685 | print('cancel_me(): after sleep') |
| 686 | |
| 687 | async def main(): |
| 688 | # Create a "cancel_me" Task |
| 689 | task = asyncio.create_task(cancel_me()) |
| 690 | |
| 691 | # Wait for 1 second |
| 692 | await asyncio.sleep(1) |
| 693 | |
| 694 | task.cancel() |
| 695 | try: |
| 696 | await task |
| 697 | except asyncio.CancelledError: |
| 698 | print("main(): cancel_me is cancelled now") |
| 699 | |
| 700 | asyncio.run(main()) |
| 701 | |
| 702 | # Expected output: |
| 703 | # |
| 704 | # cancel_me(): before sleep |
| 705 | # cancel_me(): cancel sleep |
| 706 | # cancel_me(): after sleep |
| 707 | # main(): cancel_me is cancelled now |
| 708 | |
| 709 | .. method:: cancelled() |
| 710 | |
| 711 | Return ``True`` if the Task is *cancelled*. |
| 712 | |
| 713 | The Task is *cancelled* when the cancellation was requested with |
| 714 | :meth:`cancel` and the wrapped coroutine propagated the |
| 715 | :exc:`CancelledError` exception thrown into it. |
| 716 | |
| 717 | .. method:: done() |
| 718 | |
| 719 | Return ``True`` if the Task is *done*. |
| 720 | |
| 721 | A Task is *done* when the wrapped coroutine either returned |
| 722 | a value, raised an exception, or the Task was cancelled. |
| 723 | |
Yury Selivanov | e247b46 | 2018-09-20 12:43:59 -0400 | [diff] [blame^] | 724 | .. method:: result() |
| 725 | |
| 726 | Return the result of the Task. |
| 727 | |
| 728 | If the Task is *done*, the result of the wrapped coroutine |
| 729 | is returned (or if the coroutine raised an exception, that |
| 730 | exception is re-raised.) |
| 731 | |
| 732 | If the Task has been *cancelled*, this method raises |
| 733 | a :exc:`CancelledError` exception. |
| 734 | |
| 735 | If the Task's result isn't yet available, this method raises |
| 736 | a :exc:`InvalidStateError` exception. |
| 737 | |
| 738 | .. method:: exception() |
| 739 | |
| 740 | Return the exception of the Task. |
| 741 | |
| 742 | If the wrapped coroutine raised an exception that exception |
| 743 | is returned. If the wrapped coroutine returned normally |
| 744 | this method returns ``None``. |
| 745 | |
| 746 | If the Task has been *cancelled*, this method raises a |
| 747 | :exc:`CancelledError` exception. |
| 748 | |
| 749 | If the Task isn't *done* yet, this method raises an |
| 750 | :exc:`InvalidStateError` exception. |
| 751 | |
| 752 | .. method:: add_done_callback(callback, *, context=None) |
| 753 | |
| 754 | Add a callback to be run when the Task is *done*. |
| 755 | |
| 756 | This method should only be used in low-level callback-based code. |
| 757 | |
| 758 | See the documentation of :meth:`Future.add_done_callback` |
| 759 | for more details. |
| 760 | |
| 761 | .. method:: remove_done_callback(callback) |
| 762 | |
| 763 | Remove *callback* from the callbacks list. |
| 764 | |
| 765 | This method should only be used in low-level callback-based code. |
| 766 | |
| 767 | See the documentation of :meth:`Future.remove_done_callback` |
| 768 | for more details. |
| 769 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 770 | .. method:: get_stack(\*, limit=None) |
| 771 | |
| 772 | Return the list of stack frames for this Task. |
| 773 | |
| 774 | If the wrapped coroutine is not done, this returns the stack |
| 775 | where it is suspended. If the coroutine has completed |
| 776 | successfully or was cancelled, this returns an empty list. |
| 777 | If the coroutine was terminated by an exception, this returns |
| 778 | the list of traceback frames. |
| 779 | |
| 780 | The frames are always ordered from oldest to newest. |
| 781 | |
| 782 | Only one stack frame is returned for a suspended coroutine. |
| 783 | |
| 784 | The optional *limit* argument sets the maximum number of frames |
| 785 | to return; by default all available frames are returned. |
| 786 | The ordering of the returned list differs depending on whether |
| 787 | a stack or a traceback is returned: the newest frames of a |
| 788 | stack are returned, but the oldest frames of a traceback are |
| 789 | returned. (This matches the behavior of the traceback module.) |
| 790 | |
| 791 | .. method:: print_stack(\*, limit=None, file=None) |
| 792 | |
| 793 | Print the stack or traceback for this Task. |
| 794 | |
| 795 | This produces output similar to that of the traceback module |
| 796 | for the frames retrieved by :meth:`get_stack`. |
| 797 | |
| 798 | The *limit* argument is passed to :meth:`get_stack` directly. |
| 799 | |
| 800 | The *file* argument is an I/O stream to which the output |
| 801 | is written; by default output is written to :data:`sys.stderr`. |
| 802 | |
| 803 | .. method:: get_name() |
| 804 | |
| 805 | Return the name of the Task. |
| 806 | |
| 807 | If no name has been explicitly assigned to the Task, the default |
| 808 | asyncio Task implementation generates a default name during |
| 809 | instantiation. |
| 810 | |
| 811 | .. versionadded:: 3.8 |
| 812 | |
| 813 | .. method:: set_name(value) |
| 814 | |
| 815 | Set the name of the Task. |
| 816 | |
| 817 | The *value* argument can be any object, which is then |
| 818 | converted to a string. |
| 819 | |
| 820 | In the default Task implementation, the name will be visible |
| 821 | in the :func:`repr` output of a task object. |
| 822 | |
| 823 | .. versionadded:: 3.8 |
| 824 | |
| 825 | .. classmethod:: all_tasks(loop=None) |
| 826 | |
| 827 | Return a set of all tasks for an event loop. |
| 828 | |
| 829 | By default all tasks for the current event loop are returned. |
| 830 | If *loop* is ``None``, the :func:`get_event_loop` function |
| 831 | is used to get the current loop. |
| 832 | |
Elvis Pranskevichus | 1fa2ec4 | 2018-09-17 19:16:44 -0400 | [diff] [blame] | 833 | This method is **deprecated** and will be removed in |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 834 | Python 3.9. Use the :func:`all_tasks` function instead. |
| 835 | |
| 836 | .. classmethod:: current_task(loop=None) |
| 837 | |
| 838 | Return the currently running task or ``None``. |
| 839 | |
| 840 | If *loop* is ``None``, the :func:`get_event_loop` function |
| 841 | is used to get the current loop. |
| 842 | |
Elvis Pranskevichus | 1fa2ec4 | 2018-09-17 19:16:44 -0400 | [diff] [blame] | 843 | This method is **deprecated** and will be removed in |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 844 | Python 3.9. Use the :func:`current_task` function instead. |
| 845 | |
| 846 | |
| 847 | .. _asyncio_generator_based_coro: |
| 848 | |
| 849 | Generator-based Coroutines |
| 850 | ========================== |
| 851 | |
| 852 | .. note:: |
| 853 | |
| 854 | Support for generator-based coroutines is **deprecated** and |
Elvis Pranskevichus | 1fa2ec4 | 2018-09-17 19:16:44 -0400 | [diff] [blame] | 855 | is scheduled for removal in Python 4.0. |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 856 | |
| 857 | Generator-based coroutines predate async/await syntax. They are |
Elvis Pranskevichus | 1fa2ec4 | 2018-09-17 19:16:44 -0400 | [diff] [blame] | 858 | Python generators that use ``yield from`` expressions to await |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 859 | on Futures and other coroutines. |
| 860 | |
| 861 | Generator-based coroutines should be decorated with |
| 862 | :func:`@asyncio.coroutine <asyncio.coroutine>`, although this is not |
| 863 | enforced. |
| 864 | |
| 865 | |
| 866 | .. decorator:: coroutine |
| 867 | |
| 868 | Decorator to mark generator-based coroutines. |
| 869 | |
| 870 | This decorator enables legacy generator-based coroutines to be |
| 871 | compatible with async/await code:: |
| 872 | |
| 873 | @asyncio.coroutine |
| 874 | def old_style_coroutine(): |
| 875 | yield from asyncio.sleep(1) |
| 876 | |
| 877 | async def main(): |
| 878 | await old_style_coroutine() |
| 879 | |
| 880 | This decorator is **deprecated** and is scheduled for removal in |
| 881 | Python 4.0. |
| 882 | |
| 883 | This decorator should not be used for :keyword:`async def` |
| 884 | coroutines. |
| 885 | |
| 886 | .. function:: iscoroutine(obj) |
| 887 | |
| 888 | Return ``True`` if *obj* is a :ref:`coroutine object <coroutine>`. |
| 889 | |
| 890 | This method is different from :func:`inspect.iscoroutine` because |
| 891 | it returns ``True`` for generator-based coroutines decorated with |
| 892 | :func:`@coroutine <coroutine>`. |
| 893 | |
| 894 | .. function:: iscoroutinefunction(func) |
| 895 | |
| 896 | Return ``True`` if *func* is a :ref:`coroutine function |
| 897 | <coroutine>`. |
| 898 | |
| 899 | This method is different from :func:`inspect.iscoroutinefunction` |
| 900 | because it returns ``True`` for generator-based coroutine functions |
| 901 | decorated with :func:`@coroutine <coroutine>`. |