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 | |
| 3 | Tasks and coroutines |
| 4 | ==================== |
| 5 | |
| 6 | .. _coroutine: |
| 7 | |
| 8 | Coroutines |
| 9 | ---------- |
| 10 | |
| 11 | A coroutine is a generator that follows certain conventions. For |
| 12 | documentation purposes, all coroutines should be decorated with |
| 13 | ``@asyncio.coroutine``, but this cannot be strictly enforced. |
| 14 | |
| 15 | Coroutines use the ``yield from`` syntax introduced in :pep:`380`, |
| 16 | instead of the original ``yield`` syntax. |
| 17 | |
| 18 | The word "coroutine", like the word "generator", is used for two |
| 19 | different (though related) concepts: |
| 20 | |
| 21 | - The function that defines a coroutine (a function definition |
Victor Stinner | 59759ff | 2014-01-16 19:30:21 +0100 | [diff] [blame] | 22 | decorated with ``@asyncio.coroutine``). If disambiguation is needed |
Victor Stinner | 1ad5afc | 2014-01-30 00:18:50 +0100 | [diff] [blame] | 23 | we will call this a *coroutine function* (:func:`iscoroutinefunction` |
| 24 | returns ``True``). |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 25 | |
| 26 | - The object obtained by calling a coroutine function. This object |
| 27 | represents a computation or an I/O operation (usually a combination) |
| 28 | that will complete eventually. If disambiguation is needed we will |
Victor Stinner | 1ad5afc | 2014-01-30 00:18:50 +0100 | [diff] [blame] | 29 | call it a *coroutine object* (:func:`iscoroutine` returns ``True``). |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 30 | |
| 31 | Things a coroutine can do: |
| 32 | |
| 33 | - ``result = yield from future`` -- suspends the coroutine until the |
| 34 | future is done, then returns the future's result, or raises an |
| 35 | exception, which will be propagated. (If the future is cancelled, |
| 36 | it will raise a ``CancelledError`` exception.) Note that tasks are |
| 37 | futures, and everything said about futures also applies to tasks. |
| 38 | |
| 39 | - ``result = yield from coroutine`` -- wait for another coroutine to |
| 40 | produce a result (or raise an exception, which will be propagated). |
| 41 | The ``coroutine`` expression must be a *call* to another coroutine. |
| 42 | |
| 43 | - ``return expression`` -- produce a result to the coroutine that is |
| 44 | waiting for this one using ``yield from``. |
| 45 | |
| 46 | - ``raise exception`` -- raise an exception in the coroutine that is |
| 47 | waiting for this one using ``yield from``. |
| 48 | |
| 49 | Calling a coroutine does not start its code running -- it is just a |
| 50 | generator, and the coroutine object returned by the call is really a |
| 51 | generator object, which doesn't do anything until you iterate over it. |
| 52 | In the case of a coroutine object, there are two basic ways to start |
| 53 | it running: call ``yield from coroutine`` from another coroutine |
Victor Stinner | 530ef2f | 2014-07-08 12:39:10 +0200 | [diff] [blame] | 54 | (assuming the other coroutine is already running!), or schedule its execution |
Victor Stinner | 337e03f | 2014-08-11 01:11:13 +0200 | [diff] [blame] | 55 | using the :func:`async` function or the :meth:`BaseEventLoop.create_task` |
| 56 | method. |
| 57 | |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 58 | |
| 59 | Coroutines (and tasks) can only run when the event loop is running. |
| 60 | |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 61 | .. decorator:: coroutine |
| 62 | |
| 63 | Decorator to mark coroutines. |
| 64 | |
| 65 | If the coroutine is not yielded from before it is destroyed, an error |
| 66 | message is logged. See :ref:`Detect coroutines never scheduled |
| 67 | <asyncio-coroutine-not-scheduled>`. |
| 68 | |
Yury Selivanov | 37f15bc | 2014-02-20 16:20:44 -0500 | [diff] [blame] | 69 | .. note:: |
| 70 | |
| 71 | In this documentation, some methods are documented as coroutines, |
| 72 | even if they are plain Python functions returning a :class:`Future`. |
| 73 | This is intentional to have a freedom of tweaking the implementation |
| 74 | of these functions in the future. If such a function is needed to be |
| 75 | used in a callback-style code, wrap its result with :func:`async`. |
| 76 | |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 77 | |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 78 | .. _asyncio-hello-world-coroutine: |
| 79 | |
Victor Stinner | 7f314ed | 2014-10-15 18:49:16 +0200 | [diff] [blame] | 80 | Example: Hello World coroutine |
| 81 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 82 | |
Victor Stinner | 7f314ed | 2014-10-15 18:49:16 +0200 | [diff] [blame] | 83 | Example of coroutine displaying ``"Hello World"``:: |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 84 | |
| 85 | import asyncio |
| 86 | |
| 87 | @asyncio.coroutine |
Victor Stinner | 7f314ed | 2014-10-15 18:49:16 +0200 | [diff] [blame] | 88 | def hello_world(): |
| 89 | print("Hello World!") |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 90 | |
| 91 | loop = asyncio.get_event_loop() |
Victor Stinner | 7f314ed | 2014-10-15 18:49:16 +0200 | [diff] [blame] | 92 | # Blocking call which returns when the hello_world() coroutine is done |
| 93 | loop.run_until_complete(hello_world()) |
| 94 | loop.close() |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 95 | |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 96 | .. seealso:: |
| 97 | |
Victor Stinner | 7f314ed | 2014-10-15 18:49:16 +0200 | [diff] [blame] | 98 | The :ref:`Hello World with call_soon() <asyncio-hello-world-callback>` |
| 99 | example uses the :meth:`BaseEventLoop.call_soon` method to schedule a |
| 100 | callback. |
| 101 | |
| 102 | |
| 103 | .. _asyncio-date-coroutine: |
| 104 | |
| 105 | Example: Coroutine displaying the current date |
| 106 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 107 | |
| 108 | Example of coroutine displaying the current date every second during 5 seconds |
| 109 | using the :meth:`sleep` function:: |
| 110 | |
| 111 | import asyncio |
| 112 | import datetime |
| 113 | |
| 114 | @asyncio.coroutine |
| 115 | def display_date(loop): |
| 116 | end_time = loop.time() + 5.0 |
| 117 | while True: |
| 118 | print(datetime.datetime.now()) |
| 119 | if (loop.time() + 1.0) >= end_time: |
| 120 | break |
| 121 | yield from asyncio.sleep(1) |
| 122 | |
| 123 | loop = asyncio.get_event_loop() |
| 124 | # Blocking call which returns when the display_date() coroutine is done |
| 125 | loop.run_until_complete(display_date(loop)) |
| 126 | loop.close() |
| 127 | |
| 128 | .. seealso:: |
| 129 | |
| 130 | The :ref:`display the current date with call_later() |
| 131 | <asyncio-date-callback>` example uses a callback with the |
| 132 | :meth:`BaseEventLoop.call_later` method. |
| 133 | |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 134 | |
| 135 | Example: Chain coroutines |
| 136 | ^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 137 | |
| 138 | Example chaining coroutines:: |
| 139 | |
| 140 | import asyncio |
| 141 | |
| 142 | @asyncio.coroutine |
| 143 | def compute(x, y): |
| 144 | print("Compute %s + %s ..." % (x, y)) |
| 145 | yield from asyncio.sleep(1.0) |
| 146 | return x + y |
| 147 | |
| 148 | @asyncio.coroutine |
| 149 | def print_sum(x, y): |
| 150 | result = yield from compute(x, y) |
| 151 | print("%s + %s = %s" % (x, y, result)) |
| 152 | |
| 153 | loop = asyncio.get_event_loop() |
| 154 | loop.run_until_complete(print_sum(1, 2)) |
Victor Stinner | f40c663 | 2014-01-28 23:32:40 +0100 | [diff] [blame] | 155 | loop.close() |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 156 | |
| 157 | ``compute()`` is chained to ``print_sum()``: ``print_sum()`` coroutine waits |
Brian Curtin | a1afeec | 2014-02-08 18:36:14 -0600 | [diff] [blame] | 158 | until ``compute()`` is completed before returning its result. |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 159 | |
Victor Stinner | 1c4b892 | 2013-12-12 12:35:17 +0100 | [diff] [blame] | 160 | Sequence diagram of the example: |
| 161 | |
| 162 | .. image:: tulip_coro.png |
| 163 | :align: center |
| 164 | |
Victor Stinner | 86e139a | 2013-12-13 12:51:24 +0100 | [diff] [blame] | 165 | The "Task" is created by the :meth:`BaseEventLoop.run_until_complete` method |
Victor Stinner | 59759ff | 2014-01-16 19:30:21 +0100 | [diff] [blame] | 166 | when it gets a coroutine object instead of a task. |
Victor Stinner | 86e139a | 2013-12-13 12:51:24 +0100 | [diff] [blame] | 167 | |
| 168 | The diagram shows the control flow, it does not describe exactly how things |
| 169 | work internally. For example, the sleep coroutine creates an internal future |
| 170 | which uses :meth:`BaseEventLoop.call_later` to wake up the task in 1 second. |
Victor Stinner | 1c4b892 | 2013-12-12 12:35:17 +0100 | [diff] [blame] | 171 | |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 172 | |
Victor Stinner | 99c2ab4 | 2013-12-03 19:17:25 +0100 | [diff] [blame] | 173 | InvalidStateError |
| 174 | ----------------- |
| 175 | |
| 176 | .. exception:: InvalidStateError |
| 177 | |
| 178 | The operation is not allowed in this state. |
| 179 | |
| 180 | |
Victor Stinner | 28d0ae48 | 2014-05-29 00:04:57 +0200 | [diff] [blame] | 181 | TimeoutError |
| 182 | ------------ |
| 183 | |
| 184 | .. exception:: TimeoutError |
| 185 | |
| 186 | The operation exceeded the given deadline. |
| 187 | |
| 188 | .. note:: |
| 189 | |
| 190 | This exception is different from the builtin :exc:`TimeoutError` exception! |
| 191 | |
| 192 | |
Victor Stinner | 99c2ab4 | 2013-12-03 19:17:25 +0100 | [diff] [blame] | 193 | Future |
| 194 | ------ |
| 195 | |
| 196 | .. class:: Future(\*, loop=None) |
| 197 | |
| 198 | This class is *almost* compatible with :class:`concurrent.futures.Future`. |
| 199 | |
| 200 | Differences: |
| 201 | |
| 202 | - :meth:`result` and :meth:`exception` do not take a timeout argument and |
| 203 | raise an exception when the future isn't done yet. |
| 204 | |
| 205 | - Callbacks registered with :meth:`add_done_callback` are always called |
| 206 | via the event loop's :meth:`~BaseEventLoop.call_soon_threadsafe`. |
| 207 | |
| 208 | - This class is not compatible with the :func:`~concurrent.futures.wait` and |
| 209 | :func:`~concurrent.futures.as_completed` functions in the |
| 210 | :mod:`concurrent.futures` package. |
| 211 | |
Victor Stinner | 8370496 | 2015-02-25 14:24:15 +0100 | [diff] [blame] | 212 | This class is :ref:`not thread safe <asyncio-multithreading>`. |
| 213 | |
Victor Stinner | 99c2ab4 | 2013-12-03 19:17:25 +0100 | [diff] [blame] | 214 | .. method:: cancel() |
| 215 | |
| 216 | Cancel the future and schedule callbacks. |
| 217 | |
| 218 | If the future is already done or cancelled, return ``False``. Otherwise, |
| 219 | change the future's state to cancelled, schedule the callbacks and return |
| 220 | ``True``. |
| 221 | |
| 222 | .. method:: cancelled() |
| 223 | |
| 224 | Return ``True`` if the future was cancelled. |
| 225 | |
| 226 | .. method:: done() |
| 227 | |
| 228 | Return True if the future is done. |
| 229 | |
| 230 | Done means either that a result / exception are available, or that the |
| 231 | future was cancelled. |
| 232 | |
| 233 | .. method:: result() |
| 234 | |
| 235 | Return the result this future represents. |
| 236 | |
| 237 | If the future has been cancelled, raises :exc:`CancelledError`. If the |
| 238 | future's result isn't yet available, raises :exc:`InvalidStateError`. If |
| 239 | the future is done and has an exception set, this exception is raised. |
| 240 | |
| 241 | .. method:: exception() |
| 242 | |
| 243 | Return the exception that was set on this future. |
| 244 | |
| 245 | The exception (or ``None`` if no exception was set) is returned only if |
| 246 | the future is done. If the future has been cancelled, raises |
| 247 | :exc:`CancelledError`. If the future isn't done yet, raises |
| 248 | :exc:`InvalidStateError`. |
| 249 | |
| 250 | .. method:: add_done_callback(fn) |
| 251 | |
| 252 | Add a callback to be run when the future becomes done. |
| 253 | |
| 254 | The callback is called with a single argument - the future object. If the |
| 255 | future is already done when this is called, the callback is scheduled |
| 256 | with :meth:`~BaseEventLoop.call_soon`. |
| 257 | |
Victor Stinner | 8464c24 | 2014-11-28 13:15:41 +0100 | [diff] [blame] | 258 | :ref:`Use functools.partial to pass parameters to the callback |
| 259 | <asyncio-pass-keywords>`. For example, |
| 260 | ``fut.add_done_callback(functools.partial(print, "Future:", |
| 261 | flush=True))`` will call ``print("Future:", fut, flush=True)``. |
| 262 | |
Victor Stinner | 99c2ab4 | 2013-12-03 19:17:25 +0100 | [diff] [blame] | 263 | .. method:: remove_done_callback(fn) |
| 264 | |
| 265 | Remove all instances of a callback from the "call when done" list. |
| 266 | |
| 267 | Returns the number of callbacks removed. |
| 268 | |
| 269 | .. method:: set_result(result) |
| 270 | |
| 271 | Mark the future done and set its result. |
| 272 | |
| 273 | If the future is already done when this method is called, raises |
| 274 | :exc:`InvalidStateError`. |
| 275 | |
| 276 | .. method:: set_exception(exception) |
| 277 | |
| 278 | Mark the future done and set an exception. |
| 279 | |
| 280 | If the future is already done when this method is called, raises |
| 281 | :exc:`InvalidStateError`. |
| 282 | |
| 283 | |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 284 | Example: Future with run_until_complete() |
| 285 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 286 | |
Victor Stinner | 59759ff | 2014-01-16 19:30:21 +0100 | [diff] [blame] | 287 | Example combining a :class:`Future` and a :ref:`coroutine function |
| 288 | <coroutine>`:: |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 289 | |
| 290 | import asyncio |
| 291 | |
| 292 | @asyncio.coroutine |
| 293 | def slow_operation(future): |
| 294 | yield from asyncio.sleep(1) |
Victor Stinner | 04e05da | 2014-02-17 10:54:30 +0100 | [diff] [blame] | 295 | future.set_result('Future is done!') |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 296 | |
| 297 | loop = asyncio.get_event_loop() |
| 298 | future = asyncio.Future() |
Yury Selivanov | d7e19bb | 2015-05-11 16:33:41 -0400 | [diff] [blame] | 299 | asyncio.ensure_future(slow_operation(future)) |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 300 | loop.run_until_complete(future) |
| 301 | print(future.result()) |
Victor Stinner | f40c663 | 2014-01-28 23:32:40 +0100 | [diff] [blame] | 302 | loop.close() |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 303 | |
Terry Jan Reedy | c935a95 | 2014-07-24 02:33:14 -0400 | [diff] [blame] | 304 | The coroutine function is responsible for the computation (which takes 1 second) |
Victor Stinner | 59759ff | 2014-01-16 19:30:21 +0100 | [diff] [blame] | 305 | and it stores the result into the future. The |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 306 | :meth:`~BaseEventLoop.run_until_complete` method waits for the completion of |
| 307 | the future. |
| 308 | |
| 309 | .. note:: |
| 310 | The :meth:`~BaseEventLoop.run_until_complete` method uses internally the |
| 311 | :meth:`~Future.add_done_callback` method to be notified when the future is |
| 312 | done. |
| 313 | |
| 314 | |
| 315 | Example: Future with run_forever() |
| 316 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 317 | |
| 318 | The previous example can be written differently using the |
| 319 | :meth:`Future.add_done_callback` method to describe explicitly the control |
| 320 | flow:: |
| 321 | |
| 322 | import asyncio |
| 323 | |
| 324 | @asyncio.coroutine |
| 325 | def slow_operation(future): |
| 326 | yield from asyncio.sleep(1) |
Victor Stinner | 04e05da | 2014-02-17 10:54:30 +0100 | [diff] [blame] | 327 | future.set_result('Future is done!') |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 328 | |
| 329 | def got_result(future): |
| 330 | print(future.result()) |
| 331 | loop.stop() |
| 332 | |
| 333 | loop = asyncio.get_event_loop() |
| 334 | future = asyncio.Future() |
Yury Selivanov | d7e19bb | 2015-05-11 16:33:41 -0400 | [diff] [blame] | 335 | asyncio.ensure_future(slow_operation(future)) |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 336 | future.add_done_callback(got_result) |
Victor Stinner | 04e05da | 2014-02-17 10:54:30 +0100 | [diff] [blame] | 337 | try: |
| 338 | loop.run_forever() |
| 339 | finally: |
| 340 | loop.close() |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 341 | |
Victor Stinner | 039f703 | 2014-12-02 17:52:45 +0100 | [diff] [blame] | 342 | In this example, the future is used to link ``slow_operation()`` to |
| 343 | ``got_result()``: when ``slow_operation()`` is done, ``got_result()`` is called |
| 344 | with the result. |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 345 | |
| 346 | |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 347 | Task |
| 348 | ---- |
| 349 | |
| 350 | .. class:: Task(coro, \*, loop=None) |
| 351 | |
Victor Stinner | 530ef2f | 2014-07-08 12:39:10 +0200 | [diff] [blame] | 352 | Schedule the execution of a :ref:`coroutine <coroutine>`: wrap it in a |
| 353 | future. A task is a subclass of :class:`Future`. |
| 354 | |
R David Murray | 22dd833 | 2014-09-24 11:09:09 -0400 | [diff] [blame] | 355 | A task is responsible for executing a coroutine object in an event loop. If |
Victor Stinner | 530ef2f | 2014-07-08 12:39:10 +0200 | [diff] [blame] | 356 | the wrapped coroutine yields from a future, the task suspends the execution |
| 357 | of the wrapped coroutine and waits for the completition of the future. When |
| 358 | the future is done, the execution of the wrapped coroutine restarts with the |
| 359 | result or the exception of the future. |
| 360 | |
| 361 | Event loops use cooperative scheduling: an event loop only runs one task at |
R David Murray | 22dd833 | 2014-09-24 11:09:09 -0400 | [diff] [blame] | 362 | a time. Other tasks may run in parallel if other event loops are |
Victor Stinner | 530ef2f | 2014-07-08 12:39:10 +0200 | [diff] [blame] | 363 | running in different threads. While a task waits for the completion of a |
| 364 | future, the event loop executes a new task. |
| 365 | |
R David Murray | 22dd833 | 2014-09-24 11:09:09 -0400 | [diff] [blame] | 366 | The cancellation of a task is different from the cancelation of a future. Calling |
Victor Stinner | 530ef2f | 2014-07-08 12:39:10 +0200 | [diff] [blame] | 367 | :meth:`cancel` will throw a :exc:`~concurrent.futures.CancelledError` to the |
| 368 | wrapped coroutine. :meth:`~Future.cancelled` only returns ``True`` if the |
| 369 | wrapped coroutine did not catch the |
| 370 | :exc:`~concurrent.futures.CancelledError` exception, or raised a |
| 371 | :exc:`~concurrent.futures.CancelledError` exception. |
| 372 | |
| 373 | If a pending task is destroyed, the execution of its wrapped :ref:`coroutine |
| 374 | <coroutine>` did not complete. It is probably a bug and a warning is |
| 375 | logged: see :ref:`Pending task destroyed <asyncio-pending-task-destroyed>`. |
| 376 | |
R David Murray | 22dd833 | 2014-09-24 11:09:09 -0400 | [diff] [blame] | 377 | Don't directly create :class:`Task` instances: use the :func:`async` |
Victor Stinner | 337e03f | 2014-08-11 01:11:13 +0200 | [diff] [blame] | 378 | function or the :meth:`BaseEventLoop.create_task` method. |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 379 | |
Victor Stinner | 8370496 | 2015-02-25 14:24:15 +0100 | [diff] [blame] | 380 | This class is :ref:`not thread safe <asyncio-multithreading>`. |
| 381 | |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 382 | .. classmethod:: all_tasks(loop=None) |
| 383 | |
| 384 | Return a set of all tasks for an event loop. |
| 385 | |
| 386 | By default all tasks for the current event loop are returned. |
| 387 | |
Victor Stinner | 742520b | 2013-12-10 12:14:50 +0100 | [diff] [blame] | 388 | .. classmethod:: current_task(loop=None) |
| 389 | |
| 390 | Return the currently running task in an event loop or ``None``. |
| 391 | |
| 392 | By default the current task for the current event loop is returned. |
| 393 | |
| 394 | ``None`` is returned when called not in the context of a :class:`Task`. |
| 395 | |
Victor Stinner | 8d21357 | 2014-06-02 23:06:46 +0200 | [diff] [blame] | 396 | .. method:: cancel() |
| 397 | |
R David Murray | 22dd833 | 2014-09-24 11:09:09 -0400 | [diff] [blame] | 398 | Request that this task cancel itself. |
Victor Stinner | 8d21357 | 2014-06-02 23:06:46 +0200 | [diff] [blame] | 399 | |
| 400 | This arranges for a :exc:`~concurrent.futures.CancelledError` to be |
| 401 | thrown into the wrapped coroutine on the next cycle through the event |
| 402 | loop. The coroutine then has a chance to clean up or even deny the |
| 403 | request using try/except/finally. |
| 404 | |
R David Murray | 22dd833 | 2014-09-24 11:09:09 -0400 | [diff] [blame] | 405 | Unlike :meth:`Future.cancel`, this does not guarantee that the task |
Victor Stinner | 8d21357 | 2014-06-02 23:06:46 +0200 | [diff] [blame] | 406 | will be cancelled: the exception might be caught and acted upon, delaying |
R David Murray | 22dd833 | 2014-09-24 11:09:09 -0400 | [diff] [blame] | 407 | cancellation of the task or preventing cancellation completely. The task |
| 408 | may also return a value or raise a different exception. |
Victor Stinner | 8d21357 | 2014-06-02 23:06:46 +0200 | [diff] [blame] | 409 | |
| 410 | Immediately after this method is called, :meth:`~Future.cancelled` will |
| 411 | not return ``True`` (unless the task was already cancelled). A task will |
| 412 | be marked as cancelled when the wrapped coroutine terminates with a |
| 413 | :exc:`~concurrent.futures.CancelledError` exception (even if |
| 414 | :meth:`cancel` was not called). |
| 415 | |
| 416 | .. method:: get_stack(\*, limit=None) |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 417 | |
| 418 | Return the list of stack frames for this task's coroutine. |
| 419 | |
Victor Stinner | d87de83 | 2014-12-02 17:57:04 +0100 | [diff] [blame] | 420 | If the coroutine is not done, this returns the stack where it is suspended. |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 421 | If the coroutine has completed successfully or was cancelled, this |
| 422 | returns an empty list. If the coroutine was terminated by an exception, |
| 423 | this returns the list of traceback frames. |
| 424 | |
| 425 | The frames are always ordered from oldest to newest. |
| 426 | |
Brian Curtin | a1afeec | 2014-02-08 18:36:14 -0600 | [diff] [blame] | 427 | The optional limit gives the maximum number of frames to return; by |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 428 | default all available frames are returned. Its meaning differs depending |
| 429 | on whether a stack or a traceback is returned: the newest frames of a |
| 430 | stack are returned, but the oldest frames of a traceback are returned. |
| 431 | (This matches the behavior of the traceback module.) |
| 432 | |
| 433 | For reasons beyond our control, only one stack frame is returned for a |
| 434 | suspended coroutine. |
| 435 | |
| 436 | .. method:: print_stack(\*, limit=None, file=None) |
| 437 | |
| 438 | Print the stack or traceback for this task's coroutine. |
| 439 | |
| 440 | This produces output similar to that of the traceback module, for the |
| 441 | frames retrieved by get_stack(). The limit argument is passed to |
| 442 | get_stack(). The file argument is an I/O stream to which the output |
R David Murray | 22dd833 | 2014-09-24 11:09:09 -0400 | [diff] [blame] | 443 | is written; by default output is written to sys.stderr. |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 444 | |
| 445 | |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 446 | Example: Parallel execution of tasks |
| 447 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 448 | |
| 449 | Example executing 3 tasks (A, B, C) in parallel:: |
| 450 | |
| 451 | import asyncio |
| 452 | |
| 453 | @asyncio.coroutine |
Victor Stinner | 34f2946 | 2013-12-10 02:51:05 +0100 | [diff] [blame] | 454 | def factorial(name, number): |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 455 | f = 1 |
Victor Stinner | 34f2946 | 2013-12-10 02:51:05 +0100 | [diff] [blame] | 456 | for i in range(2, number+1): |
| 457 | print("Task %s: Compute factorial(%s)..." % (name, i)) |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 458 | yield from asyncio.sleep(1) |
Victor Stinner | 34f2946 | 2013-12-10 02:51:05 +0100 | [diff] [blame] | 459 | f *= i |
| 460 | print("Task %s: factorial(%s) = %s" % (name, number, f)) |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 461 | |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 462 | loop = asyncio.get_event_loop() |
Victor Stinner | 530ef2f | 2014-07-08 12:39:10 +0200 | [diff] [blame] | 463 | tasks = [ |
Yury Selivanov | d7e19bb | 2015-05-11 16:33:41 -0400 | [diff] [blame] | 464 | asyncio.ensure_future(factorial("A", 2)), |
| 465 | asyncio.ensure_future(factorial("B", 3)), |
| 466 | asyncio.ensure_future(factorial("C", 4))] |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 467 | loop.run_until_complete(asyncio.wait(tasks)) |
Victor Stinner | f40c663 | 2014-01-28 23:32:40 +0100 | [diff] [blame] | 468 | loop.close() |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 469 | |
| 470 | Output:: |
| 471 | |
Victor Stinner | 34f2946 | 2013-12-10 02:51:05 +0100 | [diff] [blame] | 472 | Task A: Compute factorial(2)... |
| 473 | Task B: Compute factorial(2)... |
| 474 | Task C: Compute factorial(2)... |
| 475 | Task A: factorial(2) = 2 |
| 476 | Task B: Compute factorial(3)... |
| 477 | Task C: Compute factorial(3)... |
| 478 | Task B: factorial(3) = 6 |
| 479 | Task C: Compute factorial(4)... |
| 480 | Task C: factorial(4) = 24 |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 481 | |
Victor Stinner | 34f2946 | 2013-12-10 02:51:05 +0100 | [diff] [blame] | 482 | A task is automatically scheduled for execution when it is created. The event |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 483 | loop stops when all tasks are done. |
| 484 | |
| 485 | |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 486 | Task functions |
| 487 | -------------- |
| 488 | |
Eli Bendersky | 029981b | 2014-01-20 07:02:22 -0800 | [diff] [blame] | 489 | .. note:: |
| 490 | |
| 491 | In the functions below, the optional *loop* argument allows to explicitly set |
| 492 | the event loop object used by the underlying task or coroutine. If it's |
| 493 | not provided, the default event loop is used. |
| 494 | |
Victor Stinner | 99c2ab4 | 2013-12-03 19:17:25 +0100 | [diff] [blame] | 495 | .. function:: as_completed(fs, \*, loop=None, timeout=None) |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 496 | |
Victor Stinner | 99c2ab4 | 2013-12-03 19:17:25 +0100 | [diff] [blame] | 497 | Return an iterator whose values, when waited for, are :class:`Future` |
| 498 | instances. |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 499 | |
Victor Stinner | 28d0ae48 | 2014-05-29 00:04:57 +0200 | [diff] [blame] | 500 | Raises :exc:`asyncio.TimeoutError` if the timeout occurs before all Futures |
| 501 | are done. |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 502 | |
| 503 | Example:: |
| 504 | |
| 505 | for f in as_completed(fs): |
| 506 | result = yield from f # The 'yield from' may raise |
| 507 | # Use result |
| 508 | |
| 509 | .. note:: |
| 510 | |
| 511 | The futures ``f`` are not necessarily members of fs. |
| 512 | |
Yury Selivanov | d7e19bb | 2015-05-11 16:33:41 -0400 | [diff] [blame] | 513 | .. function:: ensure_future(coro_or_future, \*, loop=None) |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 514 | |
Victor Stinner | 980dd84 | 2014-10-12 21:36:17 +0200 | [diff] [blame] | 515 | Schedule the execution of a :ref:`coroutine object <coroutine>`: wrap it in |
| 516 | a future. Return a :class:`Task` object. |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 517 | |
Victor Stinner | 99c2ab4 | 2013-12-03 19:17:25 +0100 | [diff] [blame] | 518 | If the argument is a :class:`Future`, it is returned directly. |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 519 | |
Yury Selivanov | d7e19bb | 2015-05-11 16:33:41 -0400 | [diff] [blame] | 520 | .. versionadded:: 3.4.4 |
| 521 | |
Victor Stinner | 337e03f | 2014-08-11 01:11:13 +0200 | [diff] [blame] | 522 | .. seealso:: |
| 523 | |
| 524 | The :meth:`BaseEventLoop.create_task` method. |
| 525 | |
Yury Selivanov | d7e19bb | 2015-05-11 16:33:41 -0400 | [diff] [blame] | 526 | .. function:: async(coro_or_future, \*, loop=None) |
| 527 | |
| 528 | A deprecated alias to :func:`ensure_future`. |
| 529 | |
| 530 | .. deprecated:: 3.4.4 |
| 531 | |
Victor Stinner | 99c2ab4 | 2013-12-03 19:17:25 +0100 | [diff] [blame] | 532 | .. function:: gather(\*coros_or_futures, loop=None, return_exceptions=False) |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 533 | |
Victor Stinner | 59759ff | 2014-01-16 19:30:21 +0100 | [diff] [blame] | 534 | Return a future aggregating results from the given coroutine objects or |
| 535 | futures. |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 536 | |
| 537 | All futures must share the same event loop. If all the tasks are done |
| 538 | successfully, the returned future's result is the list of results (in the |
| 539 | order of the original sequence, not necessarily the order of results |
Victor Stinner | 12c68b2 | 2014-02-09 01:35:24 +0100 | [diff] [blame] | 540 | arrival). If *return_exceptions* is True, exceptions in the tasks are |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 541 | treated the same as successful results, and gathered in the result list; |
| 542 | otherwise, the first raised exception will be immediately propagated to the |
| 543 | returned future. |
| 544 | |
| 545 | Cancellation: if the outer Future is cancelled, all children (that have not |
| 546 | completed yet) are also cancelled. If any child is cancelled, this is |
| 547 | treated as if it raised :exc:`~concurrent.futures.CancelledError` -- the |
| 548 | outer Future is *not* cancelled in this case. (This is to prevent the |
| 549 | cancellation of one child to cause other children to be cancelled.) |
| 550 | |
Victor Stinner | 1ad5afc | 2014-01-30 00:18:50 +0100 | [diff] [blame] | 551 | .. function:: iscoroutine(obj) |
| 552 | |
| 553 | Return ``True`` if *obj* is a :ref:`coroutine object <coroutine>`. |
| 554 | |
| 555 | .. function:: iscoroutinefunction(obj) |
| 556 | |
| 557 | Return ``True`` if *func* is a decorated :ref:`coroutine function |
| 558 | <coroutine>`. |
| 559 | |
Victor Stinner | bdd574d | 2015-02-12 22:49:18 +0100 | [diff] [blame] | 560 | .. coroutinefunction:: sleep(delay, result=None, \*, loop=None) |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 561 | |
Yury Selivanov | 37f15bc | 2014-02-20 16:20:44 -0500 | [diff] [blame] | 562 | Create a :ref:`coroutine <coroutine>` that completes after a given |
Eli Bendersky | 2d26af8 | 2014-01-20 06:59:23 -0800 | [diff] [blame] | 563 | time (in seconds). If *result* is provided, it is produced to the caller |
| 564 | when the coroutine completes. |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 565 | |
Victor Stinner | 45b27ed | 2014-02-01 02:36:43 +0100 | [diff] [blame] | 566 | The resolution of the sleep depends on the :ref:`granularity of the event |
| 567 | loop <asyncio-delayed-calls>`. |
| 568 | |
Victor Stinner | bdd574d | 2015-02-12 22:49:18 +0100 | [diff] [blame] | 569 | This function is a :ref:`coroutine <coroutine>`. |
| 570 | |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 571 | .. function:: shield(arg, \*, loop=None) |
| 572 | |
| 573 | Wait for a future, shielding it from cancellation. |
| 574 | |
| 575 | The statement:: |
| 576 | |
| 577 | res = yield from shield(something()) |
| 578 | |
| 579 | is exactly equivalent to the statement:: |
| 580 | |
| 581 | res = yield from something() |
| 582 | |
| 583 | *except* that if the coroutine containing it is cancelled, the task running |
| 584 | in ``something()`` is not cancelled. From the point of view of |
| 585 | ``something()``, the cancellation did not happen. But its caller is still |
| 586 | cancelled, so the yield-from expression still raises |
| 587 | :exc:`~concurrent.futures.CancelledError`. Note: If ``something()`` is |
| 588 | cancelled by other means this will still cancel ``shield()``. |
| 589 | |
| 590 | If you want to completely ignore cancellation (not recommended) you can |
| 591 | combine ``shield()`` with a try/except clause, as follows:: |
| 592 | |
| 593 | try: |
| 594 | res = yield from shield(something()) |
| 595 | except CancelledError: |
| 596 | res = None |
| 597 | |
Victor Stinner | bdd574d | 2015-02-12 22:49:18 +0100 | [diff] [blame] | 598 | .. coroutinefunction:: wait(futures, \*, loop=None, timeout=None, return_when=ALL_COMPLETED) |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 599 | |
Victor Stinner | 59759ff | 2014-01-16 19:30:21 +0100 | [diff] [blame] | 600 | Wait for the Futures and coroutine objects given by the sequence *futures* |
| 601 | to complete. Coroutines will be wrapped in Tasks. Returns two sets of |
Victor Stinner | 99c2ab4 | 2013-12-03 19:17:25 +0100 | [diff] [blame] | 602 | :class:`Future`: (done, pending). |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 603 | |
Victor Stinner | db74d98 | 2014-06-10 11:16:05 +0200 | [diff] [blame] | 604 | The sequence *futures* must not be empty. |
| 605 | |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 606 | *timeout* can be used to control the maximum number of seconds to wait before |
| 607 | returning. *timeout* can be an int or float. If *timeout* is not specified |
| 608 | or ``None``, there is no limit to the wait time. |
| 609 | |
| 610 | *return_when* indicates when this function should return. It must be one of |
Victor Stinner | 933a8c8 | 2013-12-03 01:59:38 +0100 | [diff] [blame] | 611 | the following constants of the :mod:`concurrent.futures` module: |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 612 | |
| 613 | .. tabularcolumns:: |l|L| |
| 614 | |
| 615 | +-----------------------------+----------------------------------------+ |
| 616 | | Constant | Description | |
| 617 | +=============================+========================================+ |
| 618 | | :const:`FIRST_COMPLETED` | The function will return when any | |
| 619 | | | future finishes or is cancelled. | |
| 620 | +-----------------------------+----------------------------------------+ |
| 621 | | :const:`FIRST_EXCEPTION` | The function will return when any | |
| 622 | | | future finishes by raising an | |
| 623 | | | exception. If no future raises an | |
| 624 | | | exception then it is equivalent to | |
| 625 | | | :const:`ALL_COMPLETED`. | |
| 626 | +-----------------------------+----------------------------------------+ |
| 627 | | :const:`ALL_COMPLETED` | The function will return when all | |
| 628 | | | futures finish or are cancelled. | |
| 629 | +-----------------------------+----------------------------------------+ |
| 630 | |
Yury Selivanov | 37f15bc | 2014-02-20 16:20:44 -0500 | [diff] [blame] | 631 | This function is a :ref:`coroutine <coroutine>`. |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 632 | |
| 633 | Usage:: |
| 634 | |
| 635 | done, pending = yield from asyncio.wait(fs) |
| 636 | |
| 637 | .. note:: |
| 638 | |
Victor Stinner | 28d0ae48 | 2014-05-29 00:04:57 +0200 | [diff] [blame] | 639 | This does not raise :exc:`asyncio.TimeoutError`! Futures that aren't done |
| 640 | when the timeout occurs are returned in the second set. |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 641 | |
Victor Stinner | 3e09e32 | 2013-12-03 01:22:06 +0100 | [diff] [blame] | 642 | |
Victor Stinner | bdd574d | 2015-02-12 22:49:18 +0100 | [diff] [blame] | 643 | .. coroutinefunction:: wait_for(fut, timeout, \*, loop=None) |
Victor Stinner | 1ad5afc | 2014-01-30 00:18:50 +0100 | [diff] [blame] | 644 | |
| 645 | Wait for the single :class:`Future` or :ref:`coroutine object <coroutine>` |
Victor Stinner | 530ef2f | 2014-07-08 12:39:10 +0200 | [diff] [blame] | 646 | to complete with timeout. If *timeout* is ``None``, block until the future |
Victor Stinner | 1ad5afc | 2014-01-30 00:18:50 +0100 | [diff] [blame] | 647 | completes. |
| 648 | |
Victor Stinner | 337e03f | 2014-08-11 01:11:13 +0200 | [diff] [blame] | 649 | Coroutine will be wrapped in :class:`Task`. |
Victor Stinner | 1ad5afc | 2014-01-30 00:18:50 +0100 | [diff] [blame] | 650 | |
| 651 | Returns result of the Future or coroutine. When a timeout occurs, it |
Victor Stinner | 28d0ae48 | 2014-05-29 00:04:57 +0200 | [diff] [blame] | 652 | cancels the task and raises :exc:`asyncio.TimeoutError`. To avoid the task |
Victor Stinner | 1ad5afc | 2014-01-30 00:18:50 +0100 | [diff] [blame] | 653 | cancellation, wrap it in :func:`shield`. |
| 654 | |
Victor Stinner | 72dcb0a | 2015-04-03 17:08:19 +0200 | [diff] [blame] | 655 | If the wait is cancelled, the future *fut* is also cancelled. |
| 656 | |
Victor Stinner | 530ef2f | 2014-07-08 12:39:10 +0200 | [diff] [blame] | 657 | This function is a :ref:`coroutine <coroutine>`, usage:: |
Yury Selivanov | 37f15bc | 2014-02-20 16:20:44 -0500 | [diff] [blame] | 658 | |
Victor Stinner | 530ef2f | 2014-07-08 12:39:10 +0200 | [diff] [blame] | 659 | result = yield from asyncio.wait_for(fut, 60.0) |
Victor Stinner | 1ad5afc | 2014-01-30 00:18:50 +0100 | [diff] [blame] | 660 | |
Victor Stinner | 72dcb0a | 2015-04-03 17:08:19 +0200 | [diff] [blame] | 661 | .. versionchanged:: 3.4.3 |
| 662 | If the wait is cancelled, the future *fut* is now also cancelled. |
| 663 | |