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