|
| 1 | +.. currentmodule:: asyncio |
| 2 | + |
| 3 | + |
| 4 | +======= |
| 5 | +Futures |
| 6 | +======= |
| 7 | + |
| 8 | +*Future* objects are used to bridge low-level callback-based code |
| 9 | +with high-level async/await code. |
| 10 | + |
| 11 | + |
| 12 | +Future Functions |
| 13 | +================ |
| 14 | + |
| 15 | +.. function:: isfuture(obj) |
| 16 | + |
| 17 | + Return ``True`` if *obj* is either of: |
| 18 | + |
| 19 | + * an instance of :class:`asyncio.Future`, |
| 20 | + * an instance of :class:`asyncio.Task`, |
| 21 | + * a Future-like object with a ``_asyncio_future_blocking`` |
| 22 | + attribute. |
| 23 | + |
| 24 | + .. versionadded:: 3.5 |
| 25 | + |
| 26 | + |
| 27 | +.. function:: ensure_future(obj, \*, loop=None) |
| 28 | + |
| 29 | + Return: |
| 30 | + |
| 31 | + * *obj* argument as is, if *obj* is a :class:`Future`, |
| 32 | + a :class:`Task`, or a Future-like object (:func:`isfuture` |
| 33 | + is used for the test.) |
| 34 | + |
| 35 | + * a :class:`Task` object wrapping *obj*, if *obj* is a |
| 36 | + coroutine (:func:`iscoroutine` is used for the test.) |
| 37 | + |
| 38 | + * a :class:`Task` object that would await on *obj*, if *obj* is an |
| 39 | + awaitable (:func:`inspect.isawaitable` is used for the test.) |
| 40 | + |
| 41 | + If *obj* is neither of the above a :exc:`TypeError` is raised. |
| 42 | + |
| 43 | + .. important:: |
| 44 | + |
| 45 | + See also the :func:`create_task` function which is the |
| 46 | + preferred way for creating new Tasks. |
| 47 | + |
| 48 | + .. versionchanged:: 3.5.1 |
| 49 | + The function accepts any :term:`awaitable` object. |
| 50 | + |
| 51 | + |
| 52 | +.. function:: wrap_future(future, \*, loop=None) |
| 53 | + |
| 54 | + Wrap a :class:`concurrent.futures.Future` object in a |
| 55 | + :class:`asyncio.Future` object. |
| 56 | + |
| 57 | + |
| 58 | +Future Object |
| 59 | +============= |
| 60 | + |
| 61 | +.. class:: Future(\*, loop=None) |
| 62 | + |
| 63 | + A Future represents an eventual result of an asynchronous |
| 64 | + operation. Not thread-safe. |
| 65 | + |
| 66 | + Future is an :term:`awaitable` object. Coroutines can await on |
| 67 | + Future objects until they either have a result or an exception |
| 68 | + set, or until they are cancelled. |
| 69 | + |
| 70 | + Typically Futures are used to enable low-level |
| 71 | + callback-based code (e.g. in protocols implemented using asyncio |
| 72 | + :ref:`transports <asyncio-transports-protocols>`) |
| 73 | + to interoperate with high-level async/await code. |
| 74 | + |
| 75 | + The rule of thumb is to never expose Future objects in user-facing |
| 76 | + APIs, and the recommended way to create a Future object is to call |
| 77 | + :meth:`loop.create_future`. This way alternative event loop |
| 78 | + implementations can inject their own optimized implementations |
| 79 | + of a Future object. |
| 80 | + |
| 81 | + .. versionchanged:: 3.7 |
| 82 | + Added support for the :mod:`contextvars` module. |
| 83 | + |
| 84 | + .. method:: result() |
| 85 | + |
| 86 | + Return the result of the Future. |
| 87 | + |
| 88 | + If the Future is *done* and has a result set by the |
| 89 | + :meth:`set_result` method, the result value is returned. |
| 90 | + |
| 91 | + If the Future is *done* and has an exception set by the |
| 92 | + :meth:`set_exception` method, this method raises the exception. |
| 93 | + |
| 94 | + If the Future has been *cancelled*, this method raises |
| 95 | + a :exc:`CancelledError` exception. |
| 96 | + |
| 97 | + If the Future's result isn't yet available, this method raises |
| 98 | + a :exc:`InvalidStateError` exception. |
| 99 | + |
| 100 | + .. method:: set_result(result) |
| 101 | + |
| 102 | + Mark the Future as *done* and set its result. |
| 103 | + |
| 104 | + Raises a :exc:`InvalidStateError` error if the Future is |
| 105 | + already *done*. |
| 106 | + |
| 107 | + .. method:: set_exception(exception) |
| 108 | + |
| 109 | + Mark the Future as *done* and set an exception. |
| 110 | + |
| 111 | + Raises a :exc:`InvalidStateError` error if the Future is |
| 112 | + already *done*. |
| 113 | + |
| 114 | + .. method:: done() |
| 115 | + |
| 116 | + Return ``True`` if the Future is *done*. |
| 117 | + |
| 118 | + A Future is *done* if it was *cancelled* or if it has a result |
| 119 | + or an exception set with :meth:`set_result` or |
| 120 | + :meth:`set_exception` calls. |
| 121 | + |
| 122 | + .. method:: add_done_callback(callback, *, context=None) |
| 123 | + |
| 124 | + Add a callback to be run when the Future is *done*. |
| 125 | + |
| 126 | + The *callback* is called with the Future object as its only |
| 127 | + argument. |
| 128 | + |
| 129 | + If the Future is already *done* when this method is called, |
| 130 | + the callback is scheduled with :meth:`loop.call_soon`. |
| 131 | + |
| 132 | + An optional keyword-only *context* argument allows specifying a |
| 133 | + custom :class:`contextvars.Context` for the *callback* to run in. |
| 134 | + The current context is used when no *context* is provided. |
| 135 | + |
| 136 | + :func:`functools.partial` can be used to pass parameters |
| 137 | + to the callback, e.g.:: |
| 138 | + |
| 139 | + # Call 'print("Future:", fut)' when "fut" is done. |
| 140 | + fut.add_done_callback( |
| 141 | + functools.partial(print, "Future:")) |
| 142 | + |
| 143 | + .. versionchanged:: 3.7 |
| 144 | + The *context* keyword-only parameter was added. |
| 145 | + See :pep:`567` for more details. |
| 146 | + |
| 147 | + .. method:: remove_done_callback(callback) |
| 148 | + |
| 149 | + Remove *callback* from the callbacks list. |
| 150 | + |
| 151 | + Returns the number of callbacks removed, which is typically 1, |
| 152 | + unless a callback was added more than once. |
| 153 | + |
| 154 | + .. method:: cancel() |
| 155 | + |
| 156 | + Cancel the Future and schedule callbacks. |
| 157 | + |
| 158 | + If the Future is already *done* or *cancelled*, return ``False``. |
| 159 | + Otherwise, change the Future's state to *cancelled*, |
| 160 | + schedule the callbacks, and return ``True``. |
| 161 | + |
| 162 | + .. method:: exception() |
| 163 | + |
| 164 | + Return the exception that was set on this Future. |
| 165 | + |
| 166 | + The exception (or ``None`` if no exception was set) is |
| 167 | + returned only if the Future is *done*. |
| 168 | + |
| 169 | + If the Future has been *cancelled*, this method raises a |
| 170 | + :exc:`CancelledError` exception. |
| 171 | + |
| 172 | + If the Future isn't *done* yet, this method raises an |
| 173 | + :exc:`InvalidStateError` exception. |
| 174 | + |
| 175 | + .. method:: get_loop() |
| 176 | + |
| 177 | + Return the event loop the Future object is bound to. |
| 178 | + |
| 179 | + .. versionadded:: 3.7 |
| 180 | + |
| 181 | + .. method:: cancelled() |
| 182 | + |
| 183 | + Return ``True`` if the Future was *cancelled*. |
| 184 | + |
| 185 | + |
| 186 | +This example creates a Future object, creates and schedules an |
| 187 | +asynchronous Task to set result for the Future, and waits until |
| 188 | +the Future has a result:: |
| 189 | + |
| 190 | + async def set_after(fut, delay, value): |
| 191 | + # Sleep for *delay* seconds. |
| 192 | + await asyncio.sleep(delay) |
| 193 | + |
| 194 | + # Set *value* as a result of *fut* Future. |
| 195 | + fut.set_result(value) |
| 196 | + |
| 197 | + async def main(): |
| 198 | + # Get the current event loop. |
| 199 | + loop = asyncio.get_running_loop() |
| 200 | + |
| 201 | + # Create a new Future object. |
| 202 | + fut = loop.create_future() |
| 203 | + |
| 204 | + # Run "set_after()" coroutine in a parallel Task. |
| 205 | + # We are using the low-level "loop.create_task()" API here because |
| 206 | + # we already have a reference to the event loop at hand. |
| 207 | + # Otherwise we could have just used "asyncio.create_task()". |
| 208 | + loop.create_task( |
| 209 | + set_after(fut, 1, '... world')) |
| 210 | + |
| 211 | + print('hello ...') |
| 212 | + |
| 213 | + # Wait until *fut* has a result (1 second) and print it. |
| 214 | + print(await fut) |
| 215 | + |
| 216 | + asyncio.run(main()) |
| 217 | + |
| 218 | + |
| 219 | +.. important:: |
| 220 | + |
| 221 | + The Future object was designed to mimic |
| 222 | + :class:`concurrent.futures.Future`. Key differences include: |
| 223 | + |
| 224 | + - unlike asyncio Futures, :class:`concurrent.futures.Future` |
| 225 | + instances cannot be awaited. |
| 226 | + |
| 227 | + - :meth:`asyncio.Future.result` and :meth:`asyncio.Future.exception` |
| 228 | + do not accept the *timeout* argument. |
| 229 | + |
| 230 | + - :meth:`asyncio.Future.result` and :meth:`asyncio.Future.exception` |
| 231 | + raise an :exc:`InvalidStateError` exception when the Future is not |
| 232 | + *done*. |
| 233 | + |
| 234 | + - Callbacks registered with :meth:`asyncio.Future.add_done_callback` |
| 235 | + are not called immediately. They are scheduled with |
| 236 | + :meth:`loop.call_soon` instead. |
| 237 | + |
| 238 | + - asyncio Future is not compatible with the |
| 239 | + :func:`concurrent.futures.wait` and |
| 240 | + :func:`concurrent.futures.as_completed` functions. |
0 commit comments