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