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