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