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