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