1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
|
<span id="asyncio-futures"></span><h1>Futures</h1> <p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/asyncio/futures.py">Lib/asyncio/futures.py</a>, <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/asyncio/base_futures.py">Lib/asyncio/base_futures.py</a></p> <p><em>Future</em> objects are used to bridge <strong>low-level callback-based code</strong> with high-level async/await code.</p> <section id="future-functions"> <h2>Future Functions</h2> <dl class="py function"> <dt class="sig sig-object py" id="asyncio.isfuture">
<code>asyncio.isfuture(obj)</code> </dt> <dd>
<p>Return <code>True</code> if <em>obj</em> is either of:</p> <ul class="simple"> <li>an instance of <a class="reference internal" href="#asyncio.Future" title="asyncio.Future"><code>asyncio.Future</code></a>,</li> <li>an instance of <a class="reference internal" href="asyncio-task#asyncio.Task" title="asyncio.Task"><code>asyncio.Task</code></a>,</li> <li>a Future-like object with a <code>_asyncio_future_blocking</code> attribute.</li> </ul> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5.</span></p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="asyncio.ensure_future">
<code>asyncio.ensure_future(obj, *, loop=None)</code> </dt> <dd>
<p>Return:</p> <ul class="simple"> <li>
<em>obj</em> argument as is, if <em>obj</em> is a <a class="reference internal" href="#asyncio.Future" title="asyncio.Future"><code>Future</code></a>, a <a class="reference internal" href="asyncio-task#asyncio.Task" title="asyncio.Task"><code>Task</code></a>, or a Future-like object (<a class="reference internal" href="#asyncio.isfuture" title="asyncio.isfuture"><code>isfuture()</code></a> is used for the test.)</li> <li>a <a class="reference internal" href="asyncio-task#asyncio.Task" title="asyncio.Task"><code>Task</code></a> object wrapping <em>obj</em>, if <em>obj</em> is a coroutine (<a class="reference internal" href="asyncio-task#asyncio.iscoroutine" title="asyncio.iscoroutine"><code>iscoroutine()</code></a> is used for the test); in this case the coroutine will be scheduled by <code>ensure_future()</code>.</li> <li>a <a class="reference internal" href="asyncio-task#asyncio.Task" title="asyncio.Task"><code>Task</code></a> object that would await on <em>obj</em>, if <em>obj</em> is an awaitable (<a class="reference internal" href="inspect#inspect.isawaitable" title="inspect.isawaitable"><code>inspect.isawaitable()</code></a> is used for the test.)</li> </ul> <p>If <em>obj</em> is neither of the above a <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a> is raised.</p> <div class="admonition important"> <p class="admonition-title">Important</p> <p>See also the <a class="reference internal" href="asyncio-task#asyncio.create_task" title="asyncio.create_task"><code>create_task()</code></a> function which is the preferred way for creating new Tasks.</p> <p>Save a reference to the result of this function, to avoid a task disappearing mid-execution.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5.1: </span>The function accepts any <a class="reference internal" href="../glossary#term-awaitable"><span class="xref std std-term">awaitable</span></a> object.</p> </div> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.10: </span>Deprecation warning is emitted if <em>obj</em> is not a Future-like object and <em>loop</em> is not specified and there is no running event loop.</p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="asyncio.wrap_future">
<code>asyncio.wrap_future(future, *, loop=None)</code> </dt> <dd>
<p>Wrap a <a class="reference internal" href="concurrent.futures#concurrent.futures.Future" title="concurrent.futures.Future"><code>concurrent.futures.Future</code></a> object in a <a class="reference internal" href="#asyncio.Future" title="asyncio.Future"><code>asyncio.Future</code></a> object.</p> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.10: </span>Deprecation warning is emitted if <em>future</em> is not a Future-like object and <em>loop</em> is not specified and there is no running event loop.</p> </div> </dd>
</dl> </section> <section id="future-object"> <h2>Future Object</h2> <dl class="py class"> <dt class="sig sig-object py" id="asyncio.Future">
<code>class asyncio.Future(*, loop=None)</code> </dt> <dd>
<p>A Future represents an eventual result of an asynchronous operation. Not thread-safe.</p> <p>Future is an <a class="reference internal" href="../glossary#term-awaitable"><span class="xref std std-term">awaitable</span></a> object. Coroutines can await on Future objects until they either have a result or an exception set, or until they are cancelled. A Future can be awaited multiple times and the result is same.</p> <p>Typically Futures are used to enable low-level callback-based code (e.g. in protocols implemented using asyncio <a class="reference internal" href="asyncio-protocol#asyncio-transports-protocols"><span class="std std-ref">transports</span></a>) to interoperate with high-level async/await code.</p> <p>The rule of thumb is to never expose Future objects in user-facing APIs, and the recommended way to create a Future object is to call <a class="reference internal" href="asyncio-eventloop#asyncio.loop.create_future" title="asyncio.loop.create_future"><code>loop.create_future()</code></a>. This way alternative event loop implementations can inject their own optimized implementations of a Future object.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>Added support for the <a class="reference internal" href="contextvars#module-contextvars" title="contextvars: Context Variables"><code>contextvars</code></a> module.</p> </div> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.10: </span>Deprecation warning is emitted if <em>loop</em> is not specified and there is no running event loop.</p> </div> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.Future.result">
<code>result()</code> </dt> <dd>
<p>Return the result of the Future.</p> <p>If the Future is <em>done</em> and has a result set by the <a class="reference internal" href="#asyncio.Future.set_result" title="asyncio.Future.set_result"><code>set_result()</code></a> method, the result value is returned.</p> <p>If the Future is <em>done</em> and has an exception set by the <a class="reference internal" href="#asyncio.Future.set_exception" title="asyncio.Future.set_exception"><code>set_exception()</code></a> method, this method raises the exception.</p> <p>If the Future has been <em>cancelled</em>, this method raises a <a class="reference internal" href="asyncio-exceptions#asyncio.CancelledError" title="asyncio.CancelledError"><code>CancelledError</code></a> exception.</p> <p>If the Future’s result isn’t yet available, this method raises a <a class="reference internal" href="asyncio-exceptions#asyncio.InvalidStateError" title="asyncio.InvalidStateError"><code>InvalidStateError</code></a> exception.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.Future.set_result">
<code>set_result(result)</code> </dt> <dd>
<p>Mark the Future as <em>done</em> and set its result.</p> <p>Raises a <a class="reference internal" href="asyncio-exceptions#asyncio.InvalidStateError" title="asyncio.InvalidStateError"><code>InvalidStateError</code></a> error if the Future is already <em>done</em>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.Future.set_exception">
<code>set_exception(exception)</code> </dt> <dd>
<p>Mark the Future as <em>done</em> and set an exception.</p> <p>Raises a <a class="reference internal" href="asyncio-exceptions#asyncio.InvalidStateError" title="asyncio.InvalidStateError"><code>InvalidStateError</code></a> error if the Future is already <em>done</em>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.Future.done">
<code>done()</code> </dt> <dd>
<p>Return <code>True</code> if the Future is <em>done</em>.</p> <p>A Future is <em>done</em> if it was <em>cancelled</em> or if it has a result or an exception set with <a class="reference internal" href="#asyncio.Future.set_result" title="asyncio.Future.set_result"><code>set_result()</code></a> or <a class="reference internal" href="#asyncio.Future.set_exception" title="asyncio.Future.set_exception"><code>set_exception()</code></a> calls.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.Future.cancelled">
<code>cancelled()</code> </dt> <dd>
<p>Return <code>True</code> if the Future was <em>cancelled</em>.</p> <p>The method is usually used to check if a Future is not <em>cancelled</em> before setting a result or an exception for it:</p> <pre data-language="python">if not fut.cancelled():
fut.set_result(42)
</pre> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.Future.add_done_callback">
<code>add_done_callback(callback, *, context=None)</code> </dt> <dd>
<p>Add a callback to be run when the Future is <em>done</em>.</p> <p>The <em>callback</em> is called with the Future object as its only argument.</p> <p>If the Future is already <em>done</em> when this method is called, the callback is scheduled with <a class="reference internal" href="asyncio-eventloop#asyncio.loop.call_soon" title="asyncio.loop.call_soon"><code>loop.call_soon()</code></a>.</p> <p>An optional keyword-only <em>context</em> argument allows specifying a custom <a class="reference internal" href="contextvars#contextvars.Context" title="contextvars.Context"><code>contextvars.Context</code></a> for the <em>callback</em> to run in. The current context is used when no <em>context</em> is provided.</p> <p><a class="reference internal" href="functools#functools.partial" title="functools.partial"><code>functools.partial()</code></a> can be used to pass parameters to the callback, e.g.:</p> <pre data-language="python"># Call 'print("Future:", fut)' when "fut" is done.
fut.add_done_callback(
functools.partial(print, "Future:"))
</pre> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>The <em>context</em> keyword-only parameter was added. See <span class="target" id="index-0"></span><a class="pep reference external" href="https://peps.python.org/pep-0567/"><strong>PEP 567</strong></a> for more details.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.Future.remove_done_callback">
<code>remove_done_callback(callback)</code> </dt> <dd>
<p>Remove <em>callback</em> from the callbacks list.</p> <p>Returns the number of callbacks removed, which is typically 1, unless a callback was added more than once.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.Future.cancel">
<code>cancel(msg=None)</code> </dt> <dd>
<p>Cancel the Future and schedule callbacks.</p> <p>If the Future is already <em>done</em> or <em>cancelled</em>, return <code>False</code>. Otherwise, change the Future’s state to <em>cancelled</em>, schedule the callbacks, and return <code>True</code>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.9: </span>Added the <em>msg</em> parameter.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.Future.exception">
<code>exception()</code> </dt> <dd>
<p>Return the exception that was set on this Future.</p> <p>The exception (or <code>None</code> if no exception was set) is returned only if the Future is <em>done</em>.</p> <p>If the Future has been <em>cancelled</em>, this method raises a <a class="reference internal" href="asyncio-exceptions#asyncio.CancelledError" title="asyncio.CancelledError"><code>CancelledError</code></a> exception.</p> <p>If the Future isn’t <em>done</em> yet, this method raises an <a class="reference internal" href="asyncio-exceptions#asyncio.InvalidStateError" title="asyncio.InvalidStateError"><code>InvalidStateError</code></a> exception.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.Future.get_loop">
<code>get_loop()</code> </dt> <dd>
<p>Return the event loop the Future object is bound to.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.</span></p> </div> </dd>
</dl> </dd>
</dl> <p id="asyncio-example-future">This example creates a Future object, creates and schedules an asynchronous Task to set result for the Future, and waits until the Future has a result:</p> <pre data-language="python">async def set_after(fut, delay, value):
# Sleep for *delay* seconds.
await asyncio.sleep(delay)
# Set *value* as a result of *fut* Future.
fut.set_result(value)
async def main():
# Get the current event loop.
loop = asyncio.get_running_loop()
# Create a new Future object.
fut = loop.create_future()
# Run "set_after()" coroutine in a parallel Task.
# We are using the low-level "loop.create_task()" API here because
# we already have a reference to the event loop at hand.
# Otherwise we could have just used "asyncio.create_task()".
loop.create_task(
set_after(fut, 1, '... world'))
print('hello ...')
# Wait until *fut* has a result (1 second) and print it.
print(await fut)
asyncio.run(main())
</pre> <div class="admonition important"> <p class="admonition-title">Important</p> <p>The Future object was designed to mimic <a class="reference internal" href="concurrent.futures#concurrent.futures.Future" title="concurrent.futures.Future"><code>concurrent.futures.Future</code></a>. Key differences include:</p> <ul class="simple"> <li>unlike asyncio Futures, <a class="reference internal" href="concurrent.futures#concurrent.futures.Future" title="concurrent.futures.Future"><code>concurrent.futures.Future</code></a> instances cannot be awaited.</li> <li>
<a class="reference internal" href="#asyncio.Future.result" title="asyncio.Future.result"><code>asyncio.Future.result()</code></a> and <a class="reference internal" href="#asyncio.Future.exception" title="asyncio.Future.exception"><code>asyncio.Future.exception()</code></a> do not accept the <em>timeout</em> argument.</li> <li>
<a class="reference internal" href="#asyncio.Future.result" title="asyncio.Future.result"><code>asyncio.Future.result()</code></a> and <a class="reference internal" href="#asyncio.Future.exception" title="asyncio.Future.exception"><code>asyncio.Future.exception()</code></a> raise an <a class="reference internal" href="asyncio-exceptions#asyncio.InvalidStateError" title="asyncio.InvalidStateError"><code>InvalidStateError</code></a> exception when the Future is not <em>done</em>.</li> <li>Callbacks registered with <a class="reference internal" href="#asyncio.Future.add_done_callback" title="asyncio.Future.add_done_callback"><code>asyncio.Future.add_done_callback()</code></a> are not called immediately. They are scheduled with <a class="reference internal" href="asyncio-eventloop#asyncio.loop.call_soon" title="asyncio.loop.call_soon"><code>loop.call_soon()</code></a> instead.</li> <li>asyncio Future is not compatible with the <a class="reference internal" href="concurrent.futures#concurrent.futures.wait" title="concurrent.futures.wait"><code>concurrent.futures.wait()</code></a> and <a class="reference internal" href="concurrent.futures#concurrent.futures.as_completed" title="concurrent.futures.as_completed"><code>concurrent.futures.as_completed()</code></a> functions.</li> <li>
<a class="reference internal" href="#asyncio.Future.cancel" title="asyncio.Future.cancel"><code>asyncio.Future.cancel()</code></a> accepts an optional <code>msg</code> argument, but <a class="reference internal" href="concurrent.futures#concurrent.futures.Future.cancel" title="concurrent.futures.Future.cancel"><code>concurrent.futures.Future.cancel()</code></a> does not.</li> </ul> </div> </section> <div class="_attribution">
<p class="_attribution-p">
© 2001–2023 Python Software Foundation<br>Licensed under the PSF License.<br>
<a href="https://docs.python.org/3.12/library/asyncio-future.html" class="_attribution-link">https://docs.python.org/3.12/library/asyncio-future.html</a>
</p>
</div>
|