Team Ai
Apppublic

parthtamu/rag-code-assistant

sourceHugging Faceupdated 7mo agoView on Hugging Face
0likes
asyncio-future.html636 linesDownload Raw Back to docs
1<!DOCTYPE html>2 3<html lang="en" data-content_root="../">4  <head>5    <meta charset="utf-8" />6    <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" />7<meta property="og:title" content="Futures" />8<meta property="og:type" content="website" />9<meta property="og:url" content="https://docs.python.org/3/library/asyncio-future.html" />10<meta property="og:site_name" content="Python documentation" />11<meta property="og:description" content="Source code: Lib/asyncio/futures.py, Lib/asyncio/base_futures.py Future objects are used to bridge low-level callback-based code with high-level async/await code. Future Functions: Future Object: T..." />12<meta property="og:image:width" content="1146" />13<meta property="og:image:height" content="600" />14<meta property="og:image" content="https://docs.python.org/3.15/_images/social_previews/summary_library_asyncio-future_bb00f916.png" />15<meta property="og:image:alt" content="Source code: Lib/asyncio/futures.py, Lib/asyncio/base_futures.py Future objects are used to bridge low-level callback-based code with high-level async/await code. Future Functions: Future Object: T..." />16<meta name="description" content="Source code: Lib/asyncio/futures.py, Lib/asyncio/base_futures.py Future objects are used to bridge low-level callback-based code with high-level async/await code. Future Functions: Future Object: T..." />17<meta name="twitter:card" content="summary_large_image" />18<meta name="theme-color" content="#3776ab">19 20    <title>Futures &#8212; Python 3.15.0a6 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">21    22    <link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" />23    <link rel="stylesheet" type="text/css" href="../_static/classic.css?v=234b1a7c" />24    <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=89a2f22a" />25    <link rel="stylesheet" type="text/css" href="../_static/profiling-sampling-visualization.css?v=0c2600ae" />26    <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" />27    28    <script src="../_static/documentation_options.js?v=6b7c9ff5"></script>29    <script src="../_static/doctools.js?v=9bcbadda"></script>30    <script src="../_static/sphinx_highlight.js?v=dc90522c"></script>31    <script src="../_static/profiling-sampling-visualization.js?v=9811ed04"></script>32    33    <script src="../_static/sidebar.js"></script>34    35    <link rel="search" type="application/opensearchdescription+xml"36          title="Search within Python 3.15.0a6 documentation"37          href="../_static/opensearch.xml"/>38    <link rel="author" title="About these documents" href="../about.html" />39    <link rel="index" title="Index" href="../genindex.html" />40    <link rel="search" title="Search" href="../search.html" />41    <link rel="copyright" title="Copyright" href="../copyright.html" />42    <link rel="next" title="Transports and Protocols" href="asyncio-protocol.html" />43    <link rel="prev" title="Event Loop" href="asyncio-eventloop.html" />44    45      46      <script defer file-types="bz2,epub,zip" data-domain="docs.python.org" src="https://analytics.python.org/js/script.file-downloads.outbound-links.js"></script>47      48      <link rel="canonical" href="https://docs.python.org/3/library/asyncio-future.html">49      50    51 52    53    <style>54      @media only screen {55        table.full-width-table {56            width: 100%;57        }58      }59    </style>60<link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">61    <link rel="shortcut icon" type="image/png" href="../_static/py.svg">62            <script type="text/javascript" src="../_static/copybutton.js"></script>63            <script type="text/javascript" src="../_static/menu.js"></script>64            <script type="text/javascript" src="../_static/search-focus.js"></script>65            <script type="text/javascript" src="../_static/themetoggle.js"></script> 66            <script type="text/javascript" src="../_static/rtd_switcher.js"></script>67            <meta name="readthedocs-addons-api-version" content="1">68 69  </head>70<body>71<div class="mobile-nav">72    <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"73           aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu">74    <nav class="nav-content" role="navigation">75        <label for="menuToggler" class="toggler__label">76            <span></span>77        </label>78        <span class="nav-items-wrapper">79            <a href="https://www.python.org/" class="nav-logo">80                <img src="../_static/py.svg" alt="Python logo">81            </a>82            <span class="version_switcher_placeholder"></span>83            <form role="search" class="search" action="../search.html" method="get">84                <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">85                    <path fill-rule="nonzero" fill="currentColor" d="M15.5 14h-.79l-.28-.27a6.5 6.5 0 001.48-5.34c-.47-2.78-2.79-5-5.59-5.34a6.505 6.505 0 00-7.27 7.27c.34 2.8 2.56 5.12 5.34 5.59a6.5 6.5 0 005.34-1.48l.27.28v.79l4.25 4.25c.41.41 1.08.41 1.49 0 .41-.41.41-1.08 0-1.49L15.5 14zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"></path>86                </svg>87                <input placeholder="Quick search" aria-label="Quick search" type="search" name="q">88                <input type="submit" value="Go">89            </form>90        </span>91    </nav>92    <div class="menu-wrapper">93        <nav class="menu" role="navigation" aria-label="main navigation">94            <div class="language_switcher_placeholder"></div>95            96<label class="theme-selector-label">97    Theme98    <select class="theme-selector" oninput="activateTheme(this.value)">99        <option value="auto" selected>Auto</option>100        <option value="light">Light</option>101        <option value="dark">Dark</option>102    </select>103</label>104  <div>105    <h3><a href="../contents.html">Table of Contents</a></h3>106    <ul>107<li><a class="reference internal" href="#">Futures</a><ul>108<li><a class="reference internal" href="#future-functions">Future Functions</a></li>109<li><a class="reference internal" href="#future-object">Future Object</a></li>110</ul>111</li>112</ul>113 114  </div>115  <div>116    <h4>Previous topic</h4>117    <p class="topless"><a href="asyncio-eventloop.html"118                          title="previous chapter">Event Loop</a></p>119  </div>120  <div>121    <h4>Next topic</h4>122    <p class="topless"><a href="asyncio-protocol.html"123                          title="next chapter">Transports and Protocols</a></p>124  </div>125  <script>126    document.addEventListener('DOMContentLoaded', () => {127        const title = document.querySelector('meta[property="og:title"]').content;128        const elements = document.querySelectorAll('.improvepage');129        const pageurl = window.location.href.split('?')[0];130        elements.forEach(element => {131            const url = new URL(element.href.split('?')[0].replace("-nojs", ""));132            url.searchParams.set('pagetitle', title);133            url.searchParams.set('pageurl', pageurl);134            url.searchParams.set('pagesource', "library/asyncio-future.rst");135            element.href = url.toString();136        });137    });138  </script>139  <div role="note" aria-label="source link">140    <h3>This page</h3>141    <ul class="this-page-menu">142      <li><a href="../bugs.html">Report a bug</a></li>143      <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li>144      <li>145        <a href="https://github.com/python/cpython/blob/main/Doc/library/asyncio-future.rst?plain=1"146            rel="nofollow">Show source147        </a>148      </li>149      150    </ul>151  </div>152        </nav>153    </div>154</div>155 156  157    <div class="related" role="navigation" aria-label="Related">158      <h3>Navigation</h3>159      <ul>160        <li class="right" style="margin-right: 10px">161          <a href="../genindex.html" title="General Index"162             accesskey="I">index</a></li>163        <li class="right" >164          <a href="../py-modindex.html" title="Python Module Index"165             >modules</a> |</li>166        <li class="right" >167          <a href="asyncio-protocol.html" title="Transports and Protocols"168             accesskey="N">next</a> |</li>169        <li class="right" >170          <a href="asyncio-eventloop.html" title="Event Loop"171             accesskey="P">previous</a> |</li>172 173          <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li>174          <li><a href="https://www.python.org/">Python</a> &#187;</li>175          <li class="switchers">176            <div class="language_switcher_placeholder"></div>177            <div class="version_switcher_placeholder"></div>178          </li>179          <li>180              181          </li>182    <li id="cpython-language-and-version">183      <a href="../index.html">3.15.0a6 Documentation</a> &#187;184    </li>185 186          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>187          <li class="nav-item nav-item-2"><a href="ipc.html" >Networking and Interprocess Communication</a> &#187;</li>188          <li class="nav-item nav-item-3"><a href="asyncio.html" accesskey="U"><code class="xref py py-mod docutils literal notranslate"><span class="pre">asyncio</span></code> — Asynchronous I/O</a> &#187;</li>189        <li class="nav-item nav-item-this"><a href="">Futures</a></li>190                <li class="right">191                    192 193    <div class="inline-search" role="search">194        <form class="inline-search" action="../search.html" method="get">195          <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box">196          <input type="submit" value="Go">197        </form>198    </div>199                     |200                </li>201            <li class="right">202<label class="theme-selector-label">203    Theme204    <select class="theme-selector" oninput="activateTheme(this.value)">205        <option value="auto" selected>Auto</option>206        <option value="light">Light</option>207        <option value="dark">Dark</option>208    </select>209</label> |</li>210            211      </ul>212    </div>    213 214    <div class="document">215      <div class="documentwrapper">216        <div class="bodywrapper">217          <div class="body" role="main">218            219  <section id="futures">220<span id="asyncio-futures"></span><h1>Futures<a class="headerlink" href="#futures" title="Link to this heading">¶</a></h1>221<p><strong>Source code:</strong> <a class="extlink-source reference external" href="https://github.com/python/cpython/tree/main/Lib/asyncio/futures.py">Lib/asyncio/futures.py</a>,222<a class="extlink-source reference external" href="https://github.com/python/cpython/tree/main/Lib/asyncio/base_futures.py">Lib/asyncio/base_futures.py</a></p>223<hr class="docutils" />224<p><em>Future</em> objects are used to bridge <strong>low-level callback-based code</strong>225with high-level async/await code.</p>226<section id="future-functions">227<h2>Future Functions<a class="headerlink" href="#future-functions" title="Link to this heading">¶</a></h2>228<dl class="py function">229<dt class="sig sig-object py" id="asyncio.isfuture">230<span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">isfuture</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">obj</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.isfuture" title="Link to this definition">¶</a></dt>231<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if <em>obj</em> is either of:</p>232<ul class="simple">233<li><p>an instance of <a class="reference internal" href="#asyncio.Future" title="asyncio.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">asyncio.Future</span></code></a>,</p></li>234<li><p>an instance of <a class="reference internal" href="asyncio-task.html#asyncio.Task" title="asyncio.Task"><code class="xref py py-class docutils literal notranslate"><span class="pre">asyncio.Task</span></code></a>,</p></li>235<li><p>a Future-like object with a <code class="docutils literal notranslate"><span class="pre">_asyncio_future_blocking</span></code>236attribute.</p></li>237</ul>238<div class="versionadded">239<p><span class="versionmodified added">Added in version 3.5.</span></p>240</div>241</dd></dl>242 243<dl class="py function">244<dt class="sig sig-object py" id="asyncio.ensure_future">245<span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">ensure_future</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">obj</span></span></em>, <em class="sig-param"><span class="keyword-only-separator o"><abbr title="Keyword-only parameters separator (PEP 3102)"><span class="pre">*</span></abbr></span></em>, <em class="sig-param"><span class="n"><span class="pre">loop</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.ensure_future" title="Link to this definition">¶</a></dt>246<dd><p>Return:</p>247<ul class="simple">248<li><p><em>obj</em> argument as is, if <em>obj</em> is a <a class="reference internal" href="#asyncio.Future" title="asyncio.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">Future</span></code></a>,249a <a class="reference internal" href="asyncio-task.html#asyncio.Task" title="asyncio.Task"><code class="xref py py-class docutils literal notranslate"><span class="pre">Task</span></code></a>, or a Future-like object (<a class="reference internal" href="#asyncio.isfuture" title="asyncio.isfuture"><code class="xref py py-func docutils literal notranslate"><span class="pre">isfuture()</span></code></a>250is used for the test.)</p></li>251<li><p>a <a class="reference internal" href="asyncio-task.html#asyncio.Task" title="asyncio.Task"><code class="xref py py-class docutils literal notranslate"><span class="pre">Task</span></code></a> object wrapping <em>obj</em>, if <em>obj</em> is a252coroutine (<a class="reference internal" href="asyncio-task.html#asyncio.iscoroutine" title="asyncio.iscoroutine"><code class="xref py py-func docutils literal notranslate"><span class="pre">iscoroutine()</span></code></a> is used for the test);253in this case the coroutine will be scheduled by254<code class="docutils literal notranslate"><span class="pre">ensure_future()</span></code>.</p></li>255<li><p>a <a class="reference internal" href="asyncio-task.html#asyncio.Task" title="asyncio.Task"><code class="xref py py-class docutils literal notranslate"><span class="pre">Task</span></code></a> object that would await on <em>obj</em>, if <em>obj</em> is an256awaitable (<a class="reference internal" href="inspect.html#inspect.isawaitable" title="inspect.isawaitable"><code class="xref py py-func docutils literal notranslate"><span class="pre">inspect.isawaitable()</span></code></a> is used for the test.)</p></li>257</ul>258<p>If <em>obj</em> is neither of the above a <a class="reference internal" href="exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> is raised.</p>259<div class="admonition important">260<p class="admonition-title">Important</p>261<p>Save a reference to the result of this function, to avoid262a task disappearing mid-execution.</p>263<p>See also the <a class="reference internal" href="asyncio-task.html#asyncio.create_task" title="asyncio.create_task"><code class="xref py py-func docutils literal notranslate"><span class="pre">create_task()</span></code></a> function which is the264preferred way for creating new tasks or use <a class="reference internal" href="asyncio-task.html#asyncio.TaskGroup" title="asyncio.TaskGroup"><code class="xref py py-class docutils literal notranslate"><span class="pre">asyncio.TaskGroup</span></code></a>265which keeps reference to the task internally.</p>266</div>267<div class="versionchanged">268<p><span class="versionmodified changed">Changed in version 3.5.1: </span>The function accepts any <a class="reference internal" href="../glossary.html#term-awaitable"><span class="xref std std-term">awaitable</span></a> object.</p>269</div>270<div class="deprecated">271<p><span class="versionmodified deprecated">Deprecated since version 3.10: </span>Deprecation warning is emitted if <em>obj</em> is not a Future-like object272and <em>loop</em> is not specified and there is no running event loop.</p>273</div>274</dd></dl>275 276<dl class="py function">277<dt class="sig sig-object py" id="asyncio.wrap_future">278<span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">wrap_future</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">future</span></span></em>, <em class="sig-param"><span class="keyword-only-separator o"><abbr title="Keyword-only parameters separator (PEP 3102)"><span class="pre">*</span></abbr></span></em>, <em class="sig-param"><span class="n"><span class="pre">loop</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.wrap_future" title="Link to this definition">¶</a></dt>279<dd><p>Wrap a <a class="reference internal" href="concurrent.futures.html#concurrent.futures.Future" title="concurrent.futures.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">concurrent.futures.Future</span></code></a> object in a280<a class="reference internal" href="#asyncio.Future" title="asyncio.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">asyncio.Future</span></code></a> object.</p>281<div class="deprecated">282<p><span class="versionmodified deprecated">Deprecated since version 3.10: </span>Deprecation warning is emitted if <em>future</em> is not a Future-like object283and <em>loop</em> is not specified and there is no running event loop.</p>284</div>285</dd></dl>286 287</section>288<section id="future-object">289<span id="asyncio-future-obj"></span><h2>Future Object<a class="headerlink" href="#future-object" title="Link to this heading">¶</a></h2>290<dl class="py class">291<dt class="sig sig-object py" id="asyncio.Future">292<em class="property"><span class="k"><span class="pre">class</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">Future</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="keyword-only-separator o"><abbr title="Keyword-only parameters separator (PEP 3102)"><span class="pre">*</span></abbr></span></em>, <em class="sig-param"><span class="n"><span class="pre">loop</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future" title="Link to this definition">¶</a></dt>293<dd><p>A Future represents an eventual result of an asynchronous294operation.  Not thread-safe.</p>295<p>Future is an <a class="reference internal" href="../glossary.html#term-awaitable"><span class="xref std std-term">awaitable</span></a> object.  Coroutines can await on296Future objects until they either have a result or an exception297set, or until they are cancelled. A Future can be awaited multiple298times and the result is same.</p>299<p>Typically Futures are used to enable low-level300callback-based code (e.g. in protocols implemented using asyncio301<a class="reference internal" href="asyncio-protocol.html#asyncio-transports-protocols"><span class="std std-ref">transports</span></a>)302to interoperate with high-level async/await code.</p>303<p>The rule of thumb is to never expose Future objects in user-facing304APIs, and the recommended way to create a Future object is to call305<a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.create_future" title="asyncio.loop.create_future"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.create_future()</span></code></a>.  This way alternative event loop306implementations can inject their own optimized implementations307of a Future object.</p>308<div class="versionchanged">309<p><span class="versionmodified changed">Changed in version 3.7: </span>Added support for the <a class="reference internal" href="contextvars.html#module-contextvars" title="contextvars: Context Variables"><code class="xref py py-mod docutils literal notranslate"><span class="pre">contextvars</span></code></a> module.</p>310</div>311<div class="deprecated">312<p><span class="versionmodified deprecated">Deprecated since version 3.10: </span>Deprecation warning is emitted if <em>loop</em> is not specified313and there is no running event loop.</p>314</div>315<dl class="py method">316<dt class="sig sig-object py" id="asyncio.Future.result">317<span class="sig-name descname"><span class="pre">result</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future.result" title="Link to this definition">¶</a></dt>318<dd><p>Return the result of the Future.</p>319<p>If the Future is <em>done</em> and has a result set by the320<a class="reference internal" href="#asyncio.Future.set_result" title="asyncio.Future.set_result"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_result()</span></code></a> method, the result value is returned.</p>321<p>If the Future is <em>done</em> and has an exception set by the322<a class="reference internal" href="#asyncio.Future.set_exception" title="asyncio.Future.set_exception"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_exception()</span></code></a> method, this method raises the exception.</p>323<p>If the Future has been <em>cancelled</em>, this method raises324a <a class="reference internal" href="asyncio-exceptions.html#asyncio.CancelledError" title="asyncio.CancelledError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">CancelledError</span></code></a> exception.</p>325<p>If the Future’s result isn’t yet available, this method raises326an <a class="reference internal" href="asyncio-exceptions.html#asyncio.InvalidStateError" title="asyncio.InvalidStateError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">InvalidStateError</span></code></a> exception.</p>327</dd></dl>328 329<dl class="py method">330<dt class="sig sig-object py" id="asyncio.Future.set_result">331<span class="sig-name descname"><span class="pre">set_result</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">result</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future.set_result" title="Link to this definition">¶</a></dt>332<dd><p>Mark the Future as <em>done</em> and set its result.</p>333<p>Raises an <a class="reference internal" href="asyncio-exceptions.html#asyncio.InvalidStateError" title="asyncio.InvalidStateError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">InvalidStateError</span></code></a> error if the Future is334already <em>done</em>.</p>335</dd></dl>336 337<dl class="py method">338<dt class="sig sig-object py" id="asyncio.Future.set_exception">339<span class="sig-name descname"><span class="pre">set_exception</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">exception</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future.set_exception" title="Link to this definition">¶</a></dt>340<dd><p>Mark the Future as <em>done</em> and set an exception.</p>341<p>Raises an <a class="reference internal" href="asyncio-exceptions.html#asyncio.InvalidStateError" title="asyncio.InvalidStateError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">InvalidStateError</span></code></a> error if the Future is342already <em>done</em>.</p>343</dd></dl>344 345<dl class="py method">346<dt class="sig sig-object py" id="asyncio.Future.done">347<span class="sig-name descname"><span class="pre">done</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future.done" title="Link to this definition">¶</a></dt>348<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the Future is <em>done</em>.</p>349<p>A Future is <em>done</em> if it was <em>cancelled</em> or if it has a result350or an exception set with <a class="reference internal" href="#asyncio.Future.set_result" title="asyncio.Future.set_result"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_result()</span></code></a> or351<a class="reference internal" href="#asyncio.Future.set_exception" title="asyncio.Future.set_exception"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_exception()</span></code></a> calls.</p>352</dd></dl>353 354<dl class="py method">355<dt class="sig sig-object py" id="asyncio.Future.cancelled">356<span class="sig-name descname"><span class="pre">cancelled</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future.cancelled" title="Link to this definition">¶</a></dt>357<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the Future was <em>cancelled</em>.</p>358<p>The method is usually used to check if a Future is not359<em>cancelled</em> before setting a result or an exception for it:</p>360<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="ow">not</span> <span class="n">fut</span><span class="o">.</span><span class="n">cancelled</span><span class="p">():</span>361    <span class="n">fut</span><span class="o">.</span><span class="n">set_result</span><span class="p">(</span><span class="mi">42</span><span class="p">)</span>362</pre></div>363</div>364</dd></dl>365 366<dl class="py method">367<dt class="sig sig-object py" id="asyncio.Future.add_done_callback">368<span class="sig-name descname"><span class="pre">add_done_callback</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">callback</span></span></em>, <em class="sig-param"><span class="keyword-only-separator o"><abbr title="Keyword-only parameters separator (PEP 3102)"><span class="pre">*</span></abbr></span></em>, <em class="sig-param"><span class="n"><span class="pre">context</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future.add_done_callback" title="Link to this definition">¶</a></dt>369<dd><p>Add a callback to be run when the Future is <em>done</em>.</p>370<p>The <em>callback</em> is called with the Future object as its only371argument.</p>372<p>If the Future is already <em>done</em> when this method is called,373the callback is scheduled with <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.call_soon" title="asyncio.loop.call_soon"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.call_soon()</span></code></a>.</p>374<p>An optional keyword-only <em>context</em> argument allows specifying a375custom <a class="reference internal" href="contextvars.html#contextvars.Context" title="contextvars.Context"><code class="xref py py-class docutils literal notranslate"><span class="pre">contextvars.Context</span></code></a> for the <em>callback</em> to run in.376The current context is used when no <em>context</em> is provided.</p>377<p><a class="reference internal" href="functools.html#functools.partial" title="functools.partial"><code class="xref py py-func docutils literal notranslate"><span class="pre">functools.partial()</span></code></a> can be used to pass parameters378to the callback, e.g.:</p>379<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># Call &#39;print(&quot;Future:&quot;, fut)&#39; when &quot;fut&quot; is done.</span>380<span class="n">fut</span><span class="o">.</span><span class="n">add_done_callback</span><span class="p">(</span>381    <span class="n">functools</span><span class="o">.</span><span class="n">partial</span><span class="p">(</span><span class="nb">print</span><span class="p">,</span> <span class="s2">&quot;Future:&quot;</span><span class="p">))</span>382</pre></div>383</div>384<div class="versionchanged">385<p><span class="versionmodified changed">Changed in version 3.7: </span>The <em>context</em> keyword-only parameter was added.386See <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>387</div>388</dd></dl>389 390<dl class="py method">391<dt class="sig sig-object py" id="asyncio.Future.remove_done_callback">392<span class="sig-name descname"><span class="pre">remove_done_callback</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">callback</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future.remove_done_callback" title="Link to this definition">¶</a></dt>393<dd><p>Remove <em>callback</em> from the callbacks list.</p>394<p>Returns the number of callbacks removed, which is typically 1,395unless a callback was added more than once.</p>396</dd></dl>397 398<dl class="py method">399<dt class="sig sig-object py" id="asyncio.Future.cancel">400<span class="sig-name descname"><span class="pre">cancel</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">msg</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future.cancel" title="Link to this definition">¶</a></dt>401<dd><p>Cancel the Future and schedule callbacks.</p>402<p>If the Future is already <em>done</em> or <em>cancelled</em>, return <code class="docutils literal notranslate"><span class="pre">False</span></code>.403Otherwise, change the Future’s state to <em>cancelled</em>,404schedule the callbacks, and return <code class="docutils literal notranslate"><span class="pre">True</span></code>.</p>405<div class="versionchanged">406<p><span class="versionmodified changed">Changed in version 3.9: </span>Added the <em>msg</em> parameter.</p>407</div>408</dd></dl>409 410<dl class="py method">411<dt class="sig sig-object py" id="asyncio.Future.exception">412<span class="sig-name descname"><span class="pre">exception</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future.exception" title="Link to this definition">¶</a></dt>413<dd><p>Return the exception that was set on this Future.</p>414<p>The exception (or <code class="docutils literal notranslate"><span class="pre">None</span></code> if no exception was set) is415returned only if the Future is <em>done</em>.</p>416<p>If the Future has been <em>cancelled</em>, this method raises a417<a class="reference internal" href="asyncio-exceptions.html#asyncio.CancelledError" title="asyncio.CancelledError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">CancelledError</span></code></a> exception.</p>418<p>If the Future isn’t <em>done</em> yet, this method raises an419<a class="reference internal" href="asyncio-exceptions.html#asyncio.InvalidStateError" title="asyncio.InvalidStateError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">InvalidStateError</span></code></a> exception.</p>420</dd></dl>421 422<dl class="py method">423<dt class="sig sig-object py" id="asyncio.Future.get_loop">424<span class="sig-name descname"><span class="pre">get_loop</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future.get_loop" title="Link to this definition">¶</a></dt>425<dd><p>Return the event loop the Future object is bound to.</p>426<div class="versionadded">427<p><span class="versionmodified added">Added in version 3.7.</span></p>428</div>429</dd></dl>430 431</dd></dl>432 433<p id="asyncio-example-future">This example creates a Future object, creates and schedules an434asynchronous Task to set result for the Future, and waits until435the Future has a result:</p>436<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">set_after</span><span class="p">(</span><span class="n">fut</span><span class="p">,</span> <span class="n">delay</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>437    <span class="c1"># Sleep for *delay* seconds.</span>438    <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="n">delay</span><span class="p">)</span>439 440    <span class="c1"># Set *value* as a result of *fut* Future.</span>441    <span class="n">fut</span><span class="o">.</span><span class="n">set_result</span><span class="p">(</span><span class="n">value</span><span class="p">)</span>442 443<span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">main</span><span class="p">():</span>444    <span class="c1"># Get the current event loop.</span>445    <span class="n">loop</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">get_running_loop</span><span class="p">()</span>446 447    <span class="c1"># Create a new Future object.</span>448    <span class="n">fut</span> <span class="o">=</span> <span class="n">loop</span><span class="o">.</span><span class="n">create_future</span><span class="p">()</span>449 450    <span class="c1"># Run &quot;set_after()&quot; coroutine in a parallel Task.</span>451    <span class="c1"># We are using the low-level &quot;loop.create_task()&quot; API here because</span>452    <span class="c1"># we already have a reference to the event loop at hand.</span>453    <span class="c1"># Otherwise we could have just used &quot;asyncio.create_task()&quot;.</span>454    <span class="n">loop</span><span class="o">.</span><span class="n">create_task</span><span class="p">(</span>455        <span class="n">set_after</span><span class="p">(</span><span class="n">fut</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="s1">&#39;... world&#39;</span><span class="p">))</span>456 457    <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;hello ...&#39;</span><span class="p">)</span>458 459    <span class="c1"># Wait until *fut* has a result (1 second) and print it.</span>460    <span class="nb">print</span><span class="p">(</span><span class="k">await</span> <span class="n">fut</span><span class="p">)</span>461 462<span class="n">asyncio</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="n">main</span><span class="p">())</span>463</pre></div>464</div>465<div class="admonition important">466<p class="admonition-title">Important</p>467<p>The Future object was designed to mimic468<a class="reference internal" href="concurrent.futures.html#concurrent.futures.Future" title="concurrent.futures.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">concurrent.futures.Future</span></code></a>.  Key differences include:</p>469<ul class="simple">470<li><p>unlike asyncio Futures, <a class="reference internal" href="concurrent.futures.html#concurrent.futures.Future" title="concurrent.futures.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">concurrent.futures.Future</span></code></a>471instances cannot be awaited.</p></li>472<li><p><a class="reference internal" href="#asyncio.Future.result" title="asyncio.Future.result"><code class="xref py py-meth docutils literal notranslate"><span class="pre">asyncio.Future.result()</span></code></a> and <a class="reference internal" href="#asyncio.Future.exception" title="asyncio.Future.exception"><code class="xref py py-meth docutils literal notranslate"><span class="pre">asyncio.Future.exception()</span></code></a>473do not accept the <em>timeout</em> argument.</p></li>474<li><p><a class="reference internal" href="#asyncio.Future.result" title="asyncio.Future.result"><code class="xref py py-meth docutils literal notranslate"><span class="pre">asyncio.Future.result()</span></code></a> and <a class="reference internal" href="#asyncio.Future.exception" title="asyncio.Future.exception"><code class="xref py py-meth docutils literal notranslate"><span class="pre">asyncio.Future.exception()</span></code></a>475raise an <a class="reference internal" href="asyncio-exceptions.html#asyncio.InvalidStateError" title="asyncio.InvalidStateError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">InvalidStateError</span></code></a> exception when the Future is not476<em>done</em>.</p></li>477<li><p>Callbacks registered with <a class="reference internal" href="#asyncio.Future.add_done_callback" title="asyncio.Future.add_done_callback"><code class="xref py py-meth docutils literal notranslate"><span class="pre">asyncio.Future.add_done_callback()</span></code></a>478are not called immediately.  They are scheduled with479<a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.call_soon" title="asyncio.loop.call_soon"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.call_soon()</span></code></a> instead.</p></li>480<li><p>asyncio Future is not compatible with the481<a class="reference internal" href="concurrent.futures.html#concurrent.futures.wait" title="concurrent.futures.wait"><code class="xref py py-func docutils literal notranslate"><span class="pre">concurrent.futures.wait()</span></code></a> and482<a class="reference internal" href="concurrent.futures.html#concurrent.futures.as_completed" title="concurrent.futures.as_completed"><code class="xref py py-func docutils literal notranslate"><span class="pre">concurrent.futures.as_completed()</span></code></a> functions.</p></li>483<li><p><a class="reference internal" href="#asyncio.Future.cancel" title="asyncio.Future.cancel"><code class="xref py py-meth docutils literal notranslate"><span class="pre">asyncio.Future.cancel()</span></code></a> accepts an optional <code class="docutils literal notranslate"><span class="pre">msg</span></code> argument,484but <a class="reference internal" href="concurrent.futures.html#concurrent.futures.Future.cancel" title="concurrent.futures.Future.cancel"><code class="xref py py-meth docutils literal notranslate"><span class="pre">concurrent.futures.Future.cancel()</span></code></a> does not.</p></li>485</ul>486</div>487</section>488</section>489 490 491            <div class="clearer"></div>492          </div>493        </div>494      </div>495      <div class="sphinxsidebar" role="navigation" aria-label="Main">496        <div class="sphinxsidebarwrapper">497  <div>498    <h3><a href="../contents.html">Table of Contents</a></h3>499    <ul>500<li><a class="reference internal" href="#">Futures</a><ul>501<li><a class="reference internal" href="#future-functions">Future Functions</a></li>502<li><a class="reference internal" href="#future-object">Future Object</a></li>503</ul>504</li>505</ul>506 507  </div>508  <div>509    <h4>Previous topic</h4>510    <p class="topless"><a href="asyncio-eventloop.html"511                          title="previous chapter">Event Loop</a></p>512  </div>513  <div>514    <h4>Next topic</h4>515    <p class="topless"><a href="asyncio-protocol.html"516                          title="next chapter">Transports and Protocols</a></p>517  </div>518  <script>519    document.addEventListener('DOMContentLoaded', () => {520        const title = document.querySelector('meta[property="og:title"]').content;521        const elements = document.querySelectorAll('.improvepage');522        const pageurl = window.location.href.split('?')[0];523        elements.forEach(element => {524            const url = new URL(element.href.split('?')[0].replace("-nojs", ""));525            url.searchParams.set('pagetitle', title);526            url.searchParams.set('pageurl', pageurl);527            url.searchParams.set('pagesource', "library/asyncio-future.rst");528            element.href = url.toString();529        });530    });531  </script>532  <div role="note" aria-label="source link">533    <h3>This page</h3>534    <ul class="this-page-menu">535      <li><a href="../bugs.html">Report a bug</a></li>536      <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li>537      <li>538        <a href="https://github.com/python/cpython/blob/main/Doc/library/asyncio-future.rst?plain=1"539            rel="nofollow">Show source540        </a>541      </li>542      543    </ul>544  </div>545        </div>546<div id="sidebarbutton" title="Collapse sidebar">547<span>«</span>548</div>549 550      </div>551      <div class="clearer"></div>552    </div>  553    <div class="related" role="navigation" aria-label="Related">554      <h3>Navigation</h3>555      <ul>556        <li class="right" style="margin-right: 10px">557          <a href="../genindex.html" title="General Index"558             >index</a></li>559        <li class="right" >560          <a href="../py-modindex.html" title="Python Module Index"561             >modules</a> |</li>562        <li class="right" >563          <a href="asyncio-protocol.html" title="Transports and Protocols"564             >next</a> |</li>565        <li class="right" >566          <a href="asyncio-eventloop.html" title="Event Loop"567             >previous</a> |</li>568 569          <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li>570          <li><a href="https://www.python.org/">Python</a> &#187;</li>571          <li class="switchers">572            <div class="language_switcher_placeholder"></div>573            <div class="version_switcher_placeholder"></div>574          </li>575          <li>576              577          </li>578    <li id="cpython-language-and-version">579      <a href="../index.html">3.15.0a6 Documentation</a> &#187;580    </li>581 582          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>583          <li class="nav-item nav-item-2"><a href="ipc.html" >Networking and Interprocess Communication</a> &#187;</li>584          <li class="nav-item nav-item-3"><a href="asyncio.html" ><code class="xref py py-mod docutils literal notranslate"><span class="pre">asyncio</span></code> — Asynchronous I/O</a> &#187;</li>585        <li class="nav-item nav-item-this"><a href="">Futures</a></li>586                <li class="right">587                    588 589    <div class="inline-search" role="search">590        <form class="inline-search" action="../search.html" method="get">591          <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box">592          <input type="submit" value="Go">593        </form>594    </div>595                     |596                </li>597            <li class="right">598<label class="theme-selector-label">599    Theme600    <select class="theme-selector" oninput="activateTheme(this.value)">601        <option value="auto" selected>Auto</option>602        <option value="light">Light</option>603        <option value="dark">Dark</option>604    </select>605</label> |</li>606            607      </ul>608    </div>  609    <div class="footer">610    &copy; <a href="../copyright.html">Copyright</a> 2001 Python Software Foundation.611    <br>612    This page is licensed under the Python Software Foundation License Version 2.613    <br>614    Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.615    <br>616    617      See <a href="/license.html">History and License</a> for more information.<br>618    619    620    <br>621 622    The Python Software Foundation is a non-profit corporation.623<a href="https://www.python.org/psf/donations/">Please donate.</a>624<br>625    <br>626      Last updated on Mar 10, 2026 (08:58 UTC).627    628      <a href="/bugs.html">Found a bug</a>?629    630    <br>631 632    Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3.633    </div>634 635  </body>636</html>