blob: ef496a23f5cd4c5b040b55a2812bd1b4fd2ebb10 [file] [log] [blame]
Yury Selivanov3faaa882018-09-14 13:32:07 -07001.. currentmodule:: asyncio
2
3
Yury Selivanov6c731642018-09-14 14:57:39 -07004.. _asyncio-futures:
5
Yury Selivanov3faaa882018-09-14 13:32:07 -07006=======
7Futures
8=======
9
Kyle Stanleyf9000642019-10-10 19:18:46 -040010**Source code:** :source:`Lib/asyncio/futures.py`,
11:source:`Lib/asyncio/base_futures.py`
12
13-------------------------------------
14
Yury Selivanov47150392018-09-18 17:55:44 -040015*Future* objects are used to bridge **low-level callback-based code**
Yury Selivanov3faaa882018-09-14 13:32:07 -070016with 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
Andre Delfinodcc997c2020-12-16 22:37:28 -030034.. function:: ensure_future(obj, *, loop=None)
Yury Selivanov3faaa882018-09-14 13:32:07 -070035
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
Roger Iyengar092911d2019-08-21 11:59:11 -040043 coroutine (:func:`iscoroutine` is used for the test);
44 in this case the coroutine will be scheduled by
45 ``ensure_future()``.
Yury Selivanov3faaa882018-09-14 13:32:07 -070046
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
Serhiy Storchaka172c0f22021-04-25 13:40:44 +030060 .. deprecated:: 3.10
61 Deprecation warning is emitted if *obj* is not a Future-like object
62 and *loop* is not specified and there is no running event loop.
63
Yury Selivanov3faaa882018-09-14 13:32:07 -070064
Andre Delfinodcc997c2020-12-16 22:37:28 -030065.. function:: wrap_future(future, *, loop=None)
Yury Selivanov3faaa882018-09-14 13:32:07 -070066
67 Wrap a :class:`concurrent.futures.Future` object in a
68 :class:`asyncio.Future` object.
69
Serhiy Storchaka172c0f22021-04-25 13:40:44 +030070 .. deprecated:: 3.10
71 Deprecation warning is emitted if *future* is not a Future-like object
72 and *loop* is not specified and there is no running event loop.
73
Yury Selivanov3faaa882018-09-14 13:32:07 -070074
75Future Object
76=============
77
Andre Delfinodcc997c2020-12-16 22:37:28 -030078.. class:: Future(*, loop=None)
Yury Selivanov3faaa882018-09-14 13:32:07 -070079
80 A Future represents an eventual result of an asynchronous
81 operation. Not thread-safe.
82
83 Future is an :term:`awaitable` object. Coroutines can await on
84 Future objects until they either have a result or an exception
85 set, or until they are cancelled.
86
87 Typically Futures are used to enable low-level
88 callback-based code (e.g. in protocols implemented using asyncio
89 :ref:`transports <asyncio-transports-protocols>`)
90 to interoperate with high-level async/await code.
91
92 The rule of thumb is to never expose Future objects in user-facing
93 APIs, and the recommended way to create a Future object is to call
94 :meth:`loop.create_future`. This way alternative event loop
95 implementations can inject their own optimized implementations
96 of a Future object.
97
98 .. versionchanged:: 3.7
99 Added support for the :mod:`contextvars` module.
100
Serhiy Storchaka172c0f22021-04-25 13:40:44 +0300101 .. deprecated:: 3.10
102 Deprecation warning is emitted if *loop* is not specified
103 and there is no running event loop.
104
Yury Selivanov3faaa882018-09-14 13:32:07 -0700105 .. method:: result()
106
107 Return the result of the Future.
108
109 If the Future is *done* and has a result set by the
110 :meth:`set_result` method, the result value is returned.
111
112 If the Future is *done* and has an exception set by the
113 :meth:`set_exception` method, this method raises the exception.
114
115 If the Future has been *cancelled*, this method raises
116 a :exc:`CancelledError` exception.
117
118 If the Future's result isn't yet available, this method raises
119 a :exc:`InvalidStateError` exception.
120
121 .. method:: set_result(result)
122
123 Mark the Future as *done* and set its result.
124
125 Raises a :exc:`InvalidStateError` error if the Future is
126 already *done*.
127
128 .. method:: set_exception(exception)
129
130 Mark the Future as *done* and set an exception.
131
132 Raises a :exc:`InvalidStateError` error if the Future is
133 already *done*.
134
135 .. method:: done()
136
137 Return ``True`` if the Future is *done*.
138
139 A Future is *done* if it was *cancelled* or if it has a result
140 or an exception set with :meth:`set_result` or
141 :meth:`set_exception` calls.
142
Yury Selivanov805e27e2018-09-14 16:57:11 -0700143 .. method:: cancelled()
144
145 Return ``True`` if the Future was *cancelled*.
146
147 The method is usually used to check if a Future is not
148 *cancelled* before setting a result or an exception for it::
149
150 if not fut.cancelled():
151 fut.set_result(42)
152
Yury Selivanov3faaa882018-09-14 13:32:07 -0700153 .. method:: add_done_callback(callback, *, context=None)
154
155 Add a callback to be run when the Future is *done*.
156
157 The *callback* is called with the Future object as its only
158 argument.
159
160 If the Future is already *done* when this method is called,
161 the callback is scheduled with :meth:`loop.call_soon`.
162
163 An optional keyword-only *context* argument allows specifying a
164 custom :class:`contextvars.Context` for the *callback* to run in.
165 The current context is used when no *context* is provided.
166
167 :func:`functools.partial` can be used to pass parameters
168 to the callback, e.g.::
169
170 # Call 'print("Future:", fut)' when "fut" is done.
171 fut.add_done_callback(
172 functools.partial(print, "Future:"))
173
174 .. versionchanged:: 3.7
175 The *context* keyword-only parameter was added.
176 See :pep:`567` for more details.
177
178 .. method:: remove_done_callback(callback)
179
180 Remove *callback* from the callbacks list.
181
182 Returns the number of callbacks removed, which is typically 1,
183 unless a callback was added more than once.
184
Chris Jerdonek1ce58412020-05-15 16:55:50 -0700185 .. method:: cancel(msg=None)
Yury Selivanov3faaa882018-09-14 13:32:07 -0700186
187 Cancel the Future and schedule callbacks.
188
189 If the Future is already *done* or *cancelled*, return ``False``.
190 Otherwise, change the Future's state to *cancelled*,
191 schedule the callbacks, and return ``True``.
192
Chris Jerdonek1ce58412020-05-15 16:55:50 -0700193 .. versionchanged:: 3.9
194 Added the ``msg`` parameter.
195
Yury Selivanov3faaa882018-09-14 13:32:07 -0700196 .. method:: exception()
197
198 Return the exception that was set on this Future.
199
200 The exception (or ``None`` if no exception was set) is
201 returned only if the Future is *done*.
202
203 If the Future has been *cancelled*, this method raises a
204 :exc:`CancelledError` exception.
205
206 If the Future isn't *done* yet, this method raises an
207 :exc:`InvalidStateError` exception.
208
209 .. method:: get_loop()
210
211 Return the event loop the Future object is bound to.
212
213 .. versionadded:: 3.7
214
Yury Selivanov3faaa882018-09-14 13:32:07 -0700215
Yury Selivanov394374e2018-09-17 15:35:24 -0400216.. _asyncio_example_future:
217
Yury Selivanov3faaa882018-09-14 13:32:07 -0700218This example creates a Future object, creates and schedules an
219asynchronous Task to set result for the Future, and waits until
220the Future has a result::
221
222 async def set_after(fut, delay, value):
223 # Sleep for *delay* seconds.
224 await asyncio.sleep(delay)
225
226 # Set *value* as a result of *fut* Future.
227 fut.set_result(value)
228
229 async def main():
230 # Get the current event loop.
231 loop = asyncio.get_running_loop()
232
233 # Create a new Future object.
234 fut = loop.create_future()
235
236 # Run "set_after()" coroutine in a parallel Task.
237 # We are using the low-level "loop.create_task()" API here because
238 # we already have a reference to the event loop at hand.
239 # Otherwise we could have just used "asyncio.create_task()".
240 loop.create_task(
241 set_after(fut, 1, '... world'))
242
243 print('hello ...')
244
245 # Wait until *fut* has a result (1 second) and print it.
246 print(await fut)
247
248 asyncio.run(main())
249
250
251.. important::
252
253 The Future object was designed to mimic
254 :class:`concurrent.futures.Future`. Key differences include:
255
256 - unlike asyncio Futures, :class:`concurrent.futures.Future`
257 instances cannot be awaited.
258
259 - :meth:`asyncio.Future.result` and :meth:`asyncio.Future.exception`
260 do not accept the *timeout* argument.
261
262 - :meth:`asyncio.Future.result` and :meth:`asyncio.Future.exception`
263 raise an :exc:`InvalidStateError` exception when the Future is not
264 *done*.
265
266 - Callbacks registered with :meth:`asyncio.Future.add_done_callback`
267 are not called immediately. They are scheduled with
268 :meth:`loop.call_soon` instead.
269
270 - asyncio Future is not compatible with the
271 :func:`concurrent.futures.wait` and
272 :func:`concurrent.futures.as_completed` functions.
Chris Jerdonek1ce58412020-05-15 16:55:50 -0700273
274 - :meth:`asyncio.Future.cancel` accepts an optional ``msg`` argument,
275 but :func:`concurrent.futures.cancel` does not.