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