gooderp18绿色标准版
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1681 lines
146KB

  1. <!DOCTYPE html>
  2. <html lang="en" data-content_root="../">
  3. <head>
  4. <meta charset="utf-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" />
  6. <meta property="og:title" content="Coroutines and Tasks" />
  7. <meta property="og:type" content="website" />
  8. <meta property="og:url" content="https://docs.python.org/3/library/asyncio-task.html" />
  9. <meta property="og:site_name" content="Python documentation" />
  10. <meta property="og:description" content="This section outlines high-level asyncio APIs to work with coroutines and Tasks. Coroutines, Awaitables, Creating Tasks, Task Cancellation, Task Groups, Sleeping, Running Tasks Concurrently, Eager ..." />
  11. <meta property="og:image" content="https://docs.python.org/3/_static/og-image.png" />
  12. <meta property="og:image:alt" content="Python documentation" />
  13. <meta name="description" content="This section outlines high-level asyncio APIs to work with coroutines and Tasks. Coroutines, Awaitables, Creating Tasks, Task Cancellation, Task Groups, Sleeping, Running Tasks Concurrently, Eager ..." />
  14. <meta property="og:image:width" content="200" />
  15. <meta property="og:image:height" content="200" />
  16. <meta name="theme-color" content="#3776ab" />
  17. <title>Coroutines and Tasks &#8212; Python 3.12.3 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">
  18. <link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=80d5e7a1" />
  19. <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=bb723527" />
  20. <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=b20cc3f5" />
  21. <script src="../_static/documentation_options.js?v=2c828074"></script>
  22. <script src="../_static/doctools.js?v=888ff710"></script>
  23. <script src="../_static/sphinx_highlight.js?v=dc90522c"></script>
  24. <script src="../_static/sidebar.js"></script>
  25. <link rel="search" type="application/opensearchdescription+xml"
  26. title="Search within Python 3.12.3 documentation"
  27. href="../_static/opensearch.xml"/>
  28. <link rel="author" title="About these documents" href="../about.html" />
  29. <link rel="index" title="Index" href="../genindex.html" />
  30. <link rel="search" title="Search" href="../search.html" />
  31. <link rel="copyright" title="Copyright" href="../copyright.html" />
  32. <link rel="next" title="Streams" href="asyncio-stream.html" />
  33. <link rel="prev" title="Runners" href="asyncio-runner.html" />
  34. <link rel="canonical" href="https://docs.python.org/3/library/asyncio-task.html" />
  35. <style>
  36. @media only screen {
  37. table.full-width-table {
  38. width: 100%;
  39. }
  40. }
  41. </style>
  42. <link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">
  43. <link rel="shortcut icon" type="image/png" href="../_static/py.svg" />
  44. <script type="text/javascript" src="../_static/copybutton.js"></script>
  45. <script type="text/javascript" src="../_static/menu.js"></script>
  46. <script type="text/javascript" src="../_static/search-focus.js"></script>
  47. <script type="text/javascript" src="../_static/themetoggle.js"></script>
  48. </head>
  49. <body>
  50. <div class="mobile-nav">
  51. <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"
  52. aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu" />
  53. <nav class="nav-content" role="navigation">
  54. <label for="menuToggler" class="toggler__label">
  55. <span></span>
  56. </label>
  57. <span class="nav-items-wrapper">
  58. <a href="https://www.python.org/" class="nav-logo">
  59. <img src="../_static/py.svg" alt="Python logo"/>
  60. </a>
  61. <span class="version_switcher_placeholder"></span>
  62. <form role="search" class="search" action="../search.html" method="get">
  63. <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">
  64. <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>
  65. </svg>
  66. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
  67. <input type="submit" value="Go"/>
  68. </form>
  69. </span>
  70. </nav>
  71. <div class="menu-wrapper">
  72. <nav class="menu" role="navigation" aria-label="main navigation">
  73. <div class="language_switcher_placeholder"></div>
  74. <label class="theme-selector-label">
  75. Theme
  76. <select class="theme-selector" oninput="activateTheme(this.value)">
  77. <option value="auto" selected>Auto</option>
  78. <option value="light">Light</option>
  79. <option value="dark">Dark</option>
  80. </select>
  81. </label>
  82. <div>
  83. <h3><a href="../contents.html">Table of Contents</a></h3>
  84. <ul>
  85. <li><a class="reference internal" href="#">Coroutines and Tasks</a><ul>
  86. <li><a class="reference internal" href="#coroutines">Coroutines</a></li>
  87. <li><a class="reference internal" href="#awaitables">Awaitables</a></li>
  88. <li><a class="reference internal" href="#creating-tasks">Creating Tasks</a></li>
  89. <li><a class="reference internal" href="#task-cancellation">Task Cancellation</a></li>
  90. <li><a class="reference internal" href="#task-groups">Task Groups</a></li>
  91. <li><a class="reference internal" href="#sleeping">Sleeping</a></li>
  92. <li><a class="reference internal" href="#running-tasks-concurrently">Running Tasks Concurrently</a></li>
  93. <li><a class="reference internal" href="#eager-task-factory">Eager Task Factory</a></li>
  94. <li><a class="reference internal" href="#shielding-from-cancellation">Shielding From Cancellation</a></li>
  95. <li><a class="reference internal" href="#timeouts">Timeouts</a></li>
  96. <li><a class="reference internal" href="#waiting-primitives">Waiting Primitives</a></li>
  97. <li><a class="reference internal" href="#running-in-threads">Running in Threads</a></li>
  98. <li><a class="reference internal" href="#scheduling-from-other-threads">Scheduling From Other Threads</a></li>
  99. <li><a class="reference internal" href="#introspection">Introspection</a></li>
  100. <li><a class="reference internal" href="#task-object">Task Object</a></li>
  101. </ul>
  102. </li>
  103. </ul>
  104. </div>
  105. <div>
  106. <h4>Previous topic</h4>
  107. <p class="topless"><a href="asyncio-runner.html"
  108. title="previous chapter">Runners</a></p>
  109. </div>
  110. <div>
  111. <h4>Next topic</h4>
  112. <p class="topless"><a href="asyncio-stream.html"
  113. title="next chapter">Streams</a></p>
  114. </div>
  115. <div role="note" aria-label="source link">
  116. <h3>This Page</h3>
  117. <ul class="this-page-menu">
  118. <li><a href="../bugs.html">Report a Bug</a></li>
  119. <li>
  120. <a href="https://github.com/python/cpython/blob/main/Doc/library/asyncio-task.rst"
  121. rel="nofollow">Show Source
  122. </a>
  123. </li>
  124. </ul>
  125. </div>
  126. </nav>
  127. </div>
  128. </div>
  129. <div class="related" role="navigation" aria-label="related navigation">
  130. <h3>Navigation</h3>
  131. <ul>
  132. <li class="right" style="margin-right: 10px">
  133. <a href="../genindex.html" title="General Index"
  134. accesskey="I">index</a></li>
  135. <li class="right" >
  136. <a href="../py-modindex.html" title="Python Module Index"
  137. >modules</a> |</li>
  138. <li class="right" >
  139. <a href="asyncio-stream.html" title="Streams"
  140. accesskey="N">next</a> |</li>
  141. <li class="right" >
  142. <a href="asyncio-runner.html" title="Runners"
  143. accesskey="P">previous</a> |</li>
  144. <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  145. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  146. <li class="switchers">
  147. <div class="language_switcher_placeholder"></div>
  148. <div class="version_switcher_placeholder"></div>
  149. </li>
  150. <li>
  151. </li>
  152. <li id="cpython-language-and-version">
  153. <a href="../index.html">3.12.3 Documentation</a> &#187;
  154. </li>
  155. <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
  156. <li class="nav-item nav-item-2"><a href="ipc.html" >Networking and Interprocess Communication</a> &#187;</li>
  157. <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>
  158. <li class="nav-item nav-item-this"><a href="">Coroutines and Tasks</a></li>
  159. <li class="right">
  160. <div class="inline-search" role="search">
  161. <form class="inline-search" action="../search.html" method="get">
  162. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
  163. <input type="submit" value="Go" />
  164. </form>
  165. </div>
  166. |
  167. </li>
  168. <li class="right">
  169. <label class="theme-selector-label">
  170. Theme
  171. <select class="theme-selector" oninput="activateTheme(this.value)">
  172. <option value="auto" selected>Auto</option>
  173. <option value="light">Light</option>
  174. <option value="dark">Dark</option>
  175. </select>
  176. </label> |</li>
  177. </ul>
  178. </div>
  179. <div class="document">
  180. <div class="documentwrapper">
  181. <div class="bodywrapper">
  182. <div class="body" role="main">
  183. <section id="coroutines-and-tasks">
  184. <h1>Coroutines and Tasks<a class="headerlink" href="#coroutines-and-tasks" title="Link to this heading">¶</a></h1>
  185. <p>This section outlines high-level asyncio APIs to work with coroutines
  186. and Tasks.</p>
  187. <nav class="contents local" id="contents">
  188. <ul class="simple">
  189. <li><p><a class="reference internal" href="#coroutines" id="id2">Coroutines</a></p></li>
  190. <li><p><a class="reference internal" href="#awaitables" id="id3">Awaitables</a></p></li>
  191. <li><p><a class="reference internal" href="#creating-tasks" id="id4">Creating Tasks</a></p></li>
  192. <li><p><a class="reference internal" href="#task-cancellation" id="id5">Task Cancellation</a></p></li>
  193. <li><p><a class="reference internal" href="#task-groups" id="id6">Task Groups</a></p></li>
  194. <li><p><a class="reference internal" href="#sleeping" id="id7">Sleeping</a></p></li>
  195. <li><p><a class="reference internal" href="#running-tasks-concurrently" id="id8">Running Tasks Concurrently</a></p></li>
  196. <li><p><a class="reference internal" href="#eager-task-factory" id="id9">Eager Task Factory</a></p></li>
  197. <li><p><a class="reference internal" href="#shielding-from-cancellation" id="id10">Shielding From Cancellation</a></p></li>
  198. <li><p><a class="reference internal" href="#timeouts" id="id11">Timeouts</a></p></li>
  199. <li><p><a class="reference internal" href="#waiting-primitives" id="id12">Waiting Primitives</a></p></li>
  200. <li><p><a class="reference internal" href="#running-in-threads" id="id13">Running in Threads</a></p></li>
  201. <li><p><a class="reference internal" href="#scheduling-from-other-threads" id="id14">Scheduling From Other Threads</a></p></li>
  202. <li><p><a class="reference internal" href="#introspection" id="id15">Introspection</a></p></li>
  203. <li><p><a class="reference internal" href="#task-object" id="id16">Task Object</a></p></li>
  204. </ul>
  205. </nav>
  206. <section id="coroutines">
  207. <span id="coroutine"></span><h2><a class="toc-backref" href="#id2" role="doc-backlink">Coroutines</a><a class="headerlink" href="#coroutines" title="Link to this heading">¶</a></h2>
  208. <p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/asyncio/coroutines.py">Lib/asyncio/coroutines.py</a></p>
  209. <hr class="docutils" />
  210. <p><a class="reference internal" href="../glossary.html#term-coroutine"><span class="xref std std-term">Coroutines</span></a> declared with the async/await syntax is the
  211. preferred way of writing asyncio applications. For example, the following
  212. snippet of code prints “hello”, waits 1 second,
  213. and then prints “world”:</p>
  214. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">asyncio</span>
  215. <span class="gp">&gt;&gt;&gt; </span><span class="k">async</span> <span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
  216. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;hello&#39;</span><span class="p">)</span>
  217. <span class="gp">... </span> <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="mi">1</span><span class="p">)</span>
  218. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;world&#39;</span><span class="p">)</span>
  219. <span class="gp">&gt;&gt;&gt; </span><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>
  220. <span class="go">hello</span>
  221. <span class="go">world</span>
  222. </pre></div>
  223. </div>
  224. <p>Note that simply calling a coroutine will not schedule it to
  225. be executed:</p>
  226. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">main</span><span class="p">()</span>
  227. <span class="go">&lt;coroutine object main at 0x1053bb7c8&gt;</span>
  228. </pre></div>
  229. </div>
  230. <p>To actually run a coroutine, asyncio provides the following mechanisms:</p>
  231. <ul>
  232. <li><p>The <a class="reference internal" href="asyncio-runner.html#asyncio.run" title="asyncio.run"><code class="xref py py-func docutils literal notranslate"><span class="pre">asyncio.run()</span></code></a> function to run the top-level
  233. entry point “main()” function (see the above example.)</p></li>
  234. <li><p>Awaiting on a coroutine. The following snippet of code will
  235. print “hello” after waiting for 1 second, and then print “world”
  236. after waiting for <em>another</em> 2 seconds:</p>
  237. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">asyncio</span>
  238. <span class="kn">import</span> <span class="nn">time</span>
  239. <span class="k">async</span> <span class="k">def</span> <span class="nf">say_after</span><span class="p">(</span><span class="n">delay</span><span class="p">,</span> <span class="n">what</span><span class="p">):</span>
  240. <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>
  241. <span class="nb">print</span><span class="p">(</span><span class="n">what</span><span class="p">)</span>
  242. <span class="k">async</span> <span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
  243. <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">&quot;started at </span><span class="si">{</span><span class="n">time</span><span class="o">.</span><span class="n">strftime</span><span class="p">(</span><span class="s1">&#39;</span><span class="si">%X</span><span class="s1">&#39;</span><span class="p">)</span><span class="si">}</span><span class="s2">&quot;</span><span class="p">)</span>
  244. <span class="k">await</span> <span class="n">say_after</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="s1">&#39;hello&#39;</span><span class="p">)</span>
  245. <span class="k">await</span> <span class="n">say_after</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="s1">&#39;world&#39;</span><span class="p">)</span>
  246. <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">&quot;finished at </span><span class="si">{</span><span class="n">time</span><span class="o">.</span><span class="n">strftime</span><span class="p">(</span><span class="s1">&#39;</span><span class="si">%X</span><span class="s1">&#39;</span><span class="p">)</span><span class="si">}</span><span class="s2">&quot;</span><span class="p">)</span>
  247. <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>
  248. </pre></div>
  249. </div>
  250. <p>Expected output:</p>
  251. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">started</span> <span class="n">at</span> <span class="mi">17</span><span class="p">:</span><span class="mi">13</span><span class="p">:</span><span class="mi">52</span>
  252. <span class="n">hello</span>
  253. <span class="n">world</span>
  254. <span class="n">finished</span> <span class="n">at</span> <span class="mi">17</span><span class="p">:</span><span class="mi">13</span><span class="p">:</span><span class="mi">55</span>
  255. </pre></div>
  256. </div>
  257. </li>
  258. <li><p>The <a class="reference internal" href="#asyncio.create_task" title="asyncio.create_task"><code class="xref py py-func docutils literal notranslate"><span class="pre">asyncio.create_task()</span></code></a> function to run coroutines
  259. concurrently as asyncio <a class="reference internal" href="#asyncio.Task" title="asyncio.Task"><code class="xref py py-class docutils literal notranslate"><span class="pre">Tasks</span></code></a>.</p>
  260. <p>Let’s modify the above example and run two <code class="docutils literal notranslate"><span class="pre">say_after</span></code> coroutines
  261. <em>concurrently</em>:</p>
  262. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">async</span> <span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
  263. <span class="n">task1</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">create_task</span><span class="p">(</span>
  264. <span class="n">say_after</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="s1">&#39;hello&#39;</span><span class="p">))</span>
  265. <span class="n">task2</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">create_task</span><span class="p">(</span>
  266. <span class="n">say_after</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="s1">&#39;world&#39;</span><span class="p">))</span>
  267. <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">&quot;started at </span><span class="si">{</span><span class="n">time</span><span class="o">.</span><span class="n">strftime</span><span class="p">(</span><span class="s1">&#39;</span><span class="si">%X</span><span class="s1">&#39;</span><span class="p">)</span><span class="si">}</span><span class="s2">&quot;</span><span class="p">)</span>
  268. <span class="c1"># Wait until both tasks are completed (should take</span>
  269. <span class="c1"># around 2 seconds.)</span>
  270. <span class="k">await</span> <span class="n">task1</span>
  271. <span class="k">await</span> <span class="n">task2</span>
  272. <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">&quot;finished at </span><span class="si">{</span><span class="n">time</span><span class="o">.</span><span class="n">strftime</span><span class="p">(</span><span class="s1">&#39;</span><span class="si">%X</span><span class="s1">&#39;</span><span class="p">)</span><span class="si">}</span><span class="s2">&quot;</span><span class="p">)</span>
  273. </pre></div>
  274. </div>
  275. <p>Note that expected output now shows that the snippet runs
  276. 1 second faster than before:</p>
  277. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">started</span> <span class="n">at</span> <span class="mi">17</span><span class="p">:</span><span class="mi">14</span><span class="p">:</span><span class="mi">32</span>
  278. <span class="n">hello</span>
  279. <span class="n">world</span>
  280. <span class="n">finished</span> <span class="n">at</span> <span class="mi">17</span><span class="p">:</span><span class="mi">14</span><span class="p">:</span><span class="mi">34</span>
  281. </pre></div>
  282. </div>
  283. </li>
  284. <li><p>The <a class="reference internal" href="#asyncio.TaskGroup" title="asyncio.TaskGroup"><code class="xref py py-class docutils literal notranslate"><span class="pre">asyncio.TaskGroup</span></code></a> class provides a more modern
  285. alternative to <a class="reference internal" href="#asyncio.create_task" title="asyncio.create_task"><code class="xref py py-func docutils literal notranslate"><span class="pre">create_task()</span></code></a>.
  286. Using this API, the last example becomes:</p>
  287. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">async</span> <span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
  288. <span class="k">async</span> <span class="k">with</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">TaskGroup</span><span class="p">()</span> <span class="k">as</span> <span class="n">tg</span><span class="p">:</span>
  289. <span class="n">task1</span> <span class="o">=</span> <span class="n">tg</span><span class="o">.</span><span class="n">create_task</span><span class="p">(</span>
  290. <span class="n">say_after</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="s1">&#39;hello&#39;</span><span class="p">))</span>
  291. <span class="n">task2</span> <span class="o">=</span> <span class="n">tg</span><span class="o">.</span><span class="n">create_task</span><span class="p">(</span>
  292. <span class="n">say_after</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="s1">&#39;world&#39;</span><span class="p">))</span>
  293. <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">&quot;started at </span><span class="si">{</span><span class="n">time</span><span class="o">.</span><span class="n">strftime</span><span class="p">(</span><span class="s1">&#39;</span><span class="si">%X</span><span class="s1">&#39;</span><span class="p">)</span><span class="si">}</span><span class="s2">&quot;</span><span class="p">)</span>
  294. <span class="c1"># The await is implicit when the context manager exits.</span>
  295. <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">&quot;finished at </span><span class="si">{</span><span class="n">time</span><span class="o">.</span><span class="n">strftime</span><span class="p">(</span><span class="s1">&#39;</span><span class="si">%X</span><span class="s1">&#39;</span><span class="p">)</span><span class="si">}</span><span class="s2">&quot;</span><span class="p">)</span>
  296. </pre></div>
  297. </div>
  298. <p>The timing and output should be the same as for the previous version.</p>
  299. <div class="versionadded">
  300. <p><span class="versionmodified added">New in version 3.11: </span><a class="reference internal" href="#asyncio.TaskGroup" title="asyncio.TaskGroup"><code class="xref py py-class docutils literal notranslate"><span class="pre">asyncio.TaskGroup</span></code></a>.</p>
  301. </div>
  302. </li>
  303. </ul>
  304. </section>
  305. <section id="awaitables">
  306. <span id="asyncio-awaitables"></span><h2><a class="toc-backref" href="#id3" role="doc-backlink">Awaitables</a><a class="headerlink" href="#awaitables" title="Link to this heading">¶</a></h2>
  307. <p>We say that an object is an <strong>awaitable</strong> object if it can be used
  308. in an <a class="reference internal" href="../reference/expressions.html#await"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">await</span></code></a> expression. Many asyncio APIs are designed to
  309. accept awaitables.</p>
  310. <p>There are three main types of <em>awaitable</em> objects:
  311. <strong>coroutines</strong>, <strong>Tasks</strong>, and <strong>Futures</strong>.</p>
  312. <p class="rubric">Coroutines</p>
  313. <p>Python coroutines are <em>awaitables</em> and therefore can be awaited from
  314. other coroutines:</p>
  315. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">asyncio</span>
  316. <span class="k">async</span> <span class="k">def</span> <span class="nf">nested</span><span class="p">():</span>
  317. <span class="k">return</span> <span class="mi">42</span>
  318. <span class="k">async</span> <span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
  319. <span class="c1"># Nothing happens if we just call &quot;nested()&quot;.</span>
  320. <span class="c1"># A coroutine object is created but not awaited,</span>
  321. <span class="c1"># so it *won&#39;t run at all*.</span>
  322. <span class="n">nested</span><span class="p">()</span>
  323. <span class="c1"># Let&#39;s do it differently now and await it:</span>
  324. <span class="nb">print</span><span class="p">(</span><span class="k">await</span> <span class="n">nested</span><span class="p">())</span> <span class="c1"># will print &quot;42&quot;.</span>
  325. <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>
  326. </pre></div>
  327. </div>
  328. <div class="admonition important">
  329. <p class="admonition-title">Important</p>
  330. <p>In this documentation the term “coroutine” can be used for
  331. two closely related concepts:</p>
  332. <ul class="simple">
  333. <li><p>a <em>coroutine function</em>: an <a class="reference internal" href="../reference/compound_stmts.html#async-def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code></a> function;</p></li>
  334. <li><p>a <em>coroutine object</em>: an object returned by calling a
  335. <em>coroutine function</em>.</p></li>
  336. </ul>
  337. </div>
  338. <p class="rubric">Tasks</p>
  339. <p><em>Tasks</em> are used to schedule coroutines <em>concurrently</em>.</p>
  340. <p>When a coroutine is wrapped into a <em>Task</em> with functions like
  341. <a class="reference internal" href="#asyncio.create_task" title="asyncio.create_task"><code class="xref py py-func docutils literal notranslate"><span class="pre">asyncio.create_task()</span></code></a> the coroutine is automatically
  342. scheduled to run soon:</p>
  343. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">asyncio</span>
  344. <span class="k">async</span> <span class="k">def</span> <span class="nf">nested</span><span class="p">():</span>
  345. <span class="k">return</span> <span class="mi">42</span>
  346. <span class="k">async</span> <span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
  347. <span class="c1"># Schedule nested() to run soon concurrently</span>
  348. <span class="c1"># with &quot;main()&quot;.</span>
  349. <span class="n">task</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">create_task</span><span class="p">(</span><span class="n">nested</span><span class="p">())</span>
  350. <span class="c1"># &quot;task&quot; can now be used to cancel &quot;nested()&quot;, or</span>
  351. <span class="c1"># can simply be awaited to wait until it is complete:</span>
  352. <span class="k">await</span> <span class="n">task</span>
  353. <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>
  354. </pre></div>
  355. </div>
  356. <p class="rubric">Futures</p>
  357. <p>A <a class="reference internal" href="asyncio-future.html#asyncio.Future" title="asyncio.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">Future</span></code></a> is a special <strong>low-level</strong> awaitable object that
  358. represents an <strong>eventual result</strong> of an asynchronous operation.</p>
  359. <p>When a Future object is <em>awaited</em> it means that the coroutine will
  360. wait until the Future is resolved in some other place.</p>
  361. <p>Future objects in asyncio are needed to allow callback-based code
  362. to be used with async/await.</p>
  363. <p>Normally <strong>there is no need</strong> to create Future objects at the
  364. application level code.</p>
  365. <p>Future objects, sometimes exposed by libraries and some asyncio
  366. APIs, can be awaited:</p>
  367. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">async</span> <span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
  368. <span class="k">await</span> <span class="n">function_that_returns_a_future_object</span><span class="p">()</span>
  369. <span class="c1"># this is also valid:</span>
  370. <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">gather</span><span class="p">(</span>
  371. <span class="n">function_that_returns_a_future_object</span><span class="p">(),</span>
  372. <span class="n">some_python_coroutine</span><span class="p">()</span>
  373. <span class="p">)</span>
  374. </pre></div>
  375. </div>
  376. <p>A good example of a low-level function that returns a Future object
  377. is <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.run_in_executor" title="asyncio.loop.run_in_executor"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.run_in_executor()</span></code></a>.</p>
  378. </section>
  379. <section id="creating-tasks">
  380. <h2><a class="toc-backref" href="#id4" role="doc-backlink">Creating Tasks</a><a class="headerlink" href="#creating-tasks" title="Link to this heading">¶</a></h2>
  381. <p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/asyncio/tasks.py">Lib/asyncio/tasks.py</a></p>
  382. <hr class="docutils" />
  383. <dl class="py function">
  384. <dt class="sig sig-object py" id="asyncio.create_task">
  385. <span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">create_task</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">coro</span></span></em>, <em class="sig-param"><span class="o"><span class="pre">*</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">name</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></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.create_task" title="Link to this definition">¶</a></dt>
  386. <dd><p>Wrap the <em>coro</em> <a class="reference internal" href="#coroutine"><span class="std std-ref">coroutine</span></a> into a <a class="reference internal" href="#asyncio.Task" title="asyncio.Task"><code class="xref py py-class docutils literal notranslate"><span class="pre">Task</span></code></a>
  387. and schedule its execution. Return the Task object.</p>
  388. <p>If <em>name</em> is not <code class="docutils literal notranslate"><span class="pre">None</span></code>, it is set as the name of the task using
  389. <a class="reference internal" href="#asyncio.Task.set_name" title="asyncio.Task.set_name"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Task.set_name()</span></code></a>.</p>
  390. <p>An optional keyword-only <em>context</em> argument allows specifying a
  391. custom <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>coro</em> to run in.
  392. The current context copy is created when no <em>context</em> is provided.</p>
  393. <p>The task is executed in the loop returned by <a class="reference internal" href="asyncio-eventloop.html#asyncio.get_running_loop" title="asyncio.get_running_loop"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_running_loop()</span></code></a>,
  394. <a class="reference internal" href="exceptions.html#RuntimeError" title="RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> is raised if there is no running loop in
  395. current thread.</p>
  396. <div class="admonition note">
  397. <p class="admonition-title">Note</p>
  398. <p><a class="reference internal" href="#asyncio.TaskGroup.create_task" title="asyncio.TaskGroup.create_task"><code class="xref py py-meth docutils literal notranslate"><span class="pre">asyncio.TaskGroup.create_task()</span></code></a> is a new alternative
  399. leveraging structural concurrency; it allows for waiting
  400. for a group of related tasks with strong safety guarantees.</p>
  401. </div>
  402. <div class="admonition important">
  403. <p class="admonition-title">Important</p>
  404. <p>Save a reference to the result of this function, to avoid
  405. a task disappearing mid-execution. The event loop only keeps
  406. weak references to tasks. A task that isn’t referenced elsewhere
  407. may get garbage collected at any time, even before it’s done.
  408. For reliable “fire-and-forget” background tasks, gather them in
  409. a collection:</p>
  410. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">background_tasks</span> <span class="o">=</span> <span class="nb">set</span><span class="p">()</span>
  411. <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">):</span>
  412. <span class="n">task</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">create_task</span><span class="p">(</span><span class="n">some_coro</span><span class="p">(</span><span class="n">param</span><span class="o">=</span><span class="n">i</span><span class="p">))</span>
  413. <span class="c1"># Add task to the set. This creates a strong reference.</span>
  414. <span class="n">background_tasks</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">task</span><span class="p">)</span>
  415. <span class="c1"># To prevent keeping references to finished tasks forever,</span>
  416. <span class="c1"># make each task remove its own reference from the set after</span>
  417. <span class="c1"># completion:</span>
  418. <span class="n">task</span><span class="o">.</span><span class="n">add_done_callback</span><span class="p">(</span><span class="n">background_tasks</span><span class="o">.</span><span class="n">discard</span><span class="p">)</span>
  419. </pre></div>
  420. </div>
  421. </div>
  422. <div class="versionadded">
  423. <p><span class="versionmodified added">New in version 3.7.</span></p>
  424. </div>
  425. <div class="versionchanged">
  426. <p><span class="versionmodified changed">Changed in version 3.8: </span>Added the <em>name</em> parameter.</p>
  427. </div>
  428. <div class="versionchanged">
  429. <p><span class="versionmodified changed">Changed in version 3.11: </span>Added the <em>context</em> parameter.</p>
  430. </div>
  431. </dd></dl>
  432. </section>
  433. <section id="task-cancellation">
  434. <h2><a class="toc-backref" href="#id5" role="doc-backlink">Task Cancellation</a><a class="headerlink" href="#task-cancellation" title="Link to this heading">¶</a></h2>
  435. <p>Tasks can easily and safely be cancelled.
  436. When a task is cancelled, <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">asyncio.CancelledError</span></code></a> will be raised
  437. in the task at the next opportunity.</p>
  438. <p>It is recommended that coroutines use <code class="docutils literal notranslate"><span class="pre">try/finally</span></code> blocks to robustly
  439. perform clean-up logic. In case <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">asyncio.CancelledError</span></code></a>
  440. is explicitly caught, it should generally be propagated when
  441. clean-up is complete. <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">asyncio.CancelledError</span></code></a> directly subclasses
  442. <a class="reference internal" href="exceptions.html#BaseException" title="BaseException"><code class="xref py py-exc docutils literal notranslate"><span class="pre">BaseException</span></code></a> so most code will not need to be aware of it.</p>
  443. <p>The asyncio components that enable structured concurrency, like
  444. <a class="reference internal" href="#asyncio.TaskGroup" title="asyncio.TaskGroup"><code class="xref py py-class docutils literal notranslate"><span class="pre">asyncio.TaskGroup</span></code></a> and <a class="reference internal" href="#asyncio.timeout" title="asyncio.timeout"><code class="xref py py-func docutils literal notranslate"><span class="pre">asyncio.timeout()</span></code></a>,
  445. are implemented using cancellation internally and might misbehave if
  446. a coroutine swallows <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">asyncio.CancelledError</span></code></a>. Similarly, user code
  447. should not generally call <a class="reference internal" href="#asyncio.Task.uncancel" title="asyncio.Task.uncancel"><code class="xref py py-meth docutils literal notranslate"><span class="pre">uncancel</span></code></a>.
  448. However, in cases when suppressing <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">asyncio.CancelledError</span></code></a> is
  449. truly desired, it is necessary to also call <code class="docutils literal notranslate"><span class="pre">uncancel()</span></code> to completely
  450. remove the cancellation state.</p>
  451. </section>
  452. <section id="task-groups">
  453. <span id="taskgroups"></span><h2><a class="toc-backref" href="#id6" role="doc-backlink">Task Groups</a><a class="headerlink" href="#task-groups" title="Link to this heading">¶</a></h2>
  454. <p>Task groups combine a task creation API with a convenient
  455. and reliable way to wait for all tasks in the group to finish.</p>
  456. <dl class="py class">
  457. <dt class="sig sig-object py" id="asyncio.TaskGroup">
  458. <em class="property"><span class="pre">class</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">TaskGroup</span></span><a class="headerlink" href="#asyncio.TaskGroup" title="Link to this definition">¶</a></dt>
  459. <dd><p>An <a class="reference internal" href="../reference/datamodel.html#async-context-managers"><span class="std std-ref">asynchronous context manager</span></a>
  460. holding a group of tasks.
  461. Tasks can be added to the group using <a class="reference internal" href="#asyncio.create_task" title="asyncio.create_task"><code class="xref py py-meth docutils literal notranslate"><span class="pre">create_task()</span></code></a>.
  462. All tasks are awaited when the context manager exits.</p>
  463. <div class="versionadded">
  464. <p><span class="versionmodified added">New in version 3.11.</span></p>
  465. </div>
  466. <dl class="py method">
  467. <dt class="sig sig-object py" id="asyncio.TaskGroup.create_task">
  468. <span class="sig-name descname"><span class="pre">create_task</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">coro</span></span></em>, <em class="sig-param"><span class="o"><span class="pre">*</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">name</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></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.TaskGroup.create_task" title="Link to this definition">¶</a></dt>
  469. <dd><p>Create a task in this task group.
  470. The signature matches that of <a class="reference internal" href="#asyncio.create_task" title="asyncio.create_task"><code class="xref py py-func docutils literal notranslate"><span class="pre">asyncio.create_task()</span></code></a>.</p>
  471. </dd></dl>
  472. </dd></dl>
  473. <p>Example:</p>
  474. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">async</span> <span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
  475. <span class="k">async</span> <span class="k">with</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">TaskGroup</span><span class="p">()</span> <span class="k">as</span> <span class="n">tg</span><span class="p">:</span>
  476. <span class="n">task1</span> <span class="o">=</span> <span class="n">tg</span><span class="o">.</span><span class="n">create_task</span><span class="p">(</span><span class="n">some_coro</span><span class="p">(</span><span class="o">...</span><span class="p">))</span>
  477. <span class="n">task2</span> <span class="o">=</span> <span class="n">tg</span><span class="o">.</span><span class="n">create_task</span><span class="p">(</span><span class="n">another_coro</span><span class="p">(</span><span class="o">...</span><span class="p">))</span>
  478. <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">&quot;Both tasks have completed now: </span><span class="si">{</span><span class="n">task1</span><span class="o">.</span><span class="n">result</span><span class="p">()</span><span class="si">}</span><span class="s2">, </span><span class="si">{</span><span class="n">task2</span><span class="o">.</span><span class="n">result</span><span class="p">()</span><span class="si">}</span><span class="s2">&quot;</span><span class="p">)</span>
  479. </pre></div>
  480. </div>
  481. <p>The <code class="docutils literal notranslate"><span class="pre">async</span> <span class="pre">with</span></code> statement will wait for all tasks in the group to finish.
  482. While waiting, new tasks may still be added to the group
  483. (for example, by passing <code class="docutils literal notranslate"><span class="pre">tg</span></code> into one of the coroutines
  484. and calling <code class="docutils literal notranslate"><span class="pre">tg.create_task()</span></code> in that coroutine).
  485. Once the last task has finished and the <code class="docutils literal notranslate"><span class="pre">async</span> <span class="pre">with</span></code> block is exited,
  486. no new tasks may be added to the group.</p>
  487. <p>The first time any of the tasks belonging to the group fails
  488. with an exception other than <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">asyncio.CancelledError</span></code></a>,
  489. the remaining tasks in the group are cancelled.
  490. No further tasks can then be added to the group.
  491. At this point, if the body of the <code class="docutils literal notranslate"><span class="pre">async</span> <span class="pre">with</span></code> statement is still active
  492. (i.e., <a class="reference internal" href="../reference/datamodel.html#object.__aexit__" title="object.__aexit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__aexit__()</span></code></a> hasn’t been called yet),
  493. the task directly containing the <code class="docutils literal notranslate"><span class="pre">async</span> <span class="pre">with</span></code> statement is also cancelled.
  494. The resulting <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">asyncio.CancelledError</span></code></a> will interrupt an <code class="docutils literal notranslate"><span class="pre">await</span></code>,
  495. but it will not bubble out of the containing <code class="docutils literal notranslate"><span class="pre">async</span> <span class="pre">with</span></code> statement.</p>
  496. <p>Once all tasks have finished, if any tasks have failed
  497. with an exception other than <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">asyncio.CancelledError</span></code></a>,
  498. those exceptions are combined in an
  499. <a class="reference internal" href="exceptions.html#ExceptionGroup" title="ExceptionGroup"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ExceptionGroup</span></code></a> or <a class="reference internal" href="exceptions.html#BaseExceptionGroup" title="BaseExceptionGroup"><code class="xref py py-exc docutils literal notranslate"><span class="pre">BaseExceptionGroup</span></code></a>
  500. (as appropriate; see their documentation)
  501. which is then raised.</p>
  502. <p>Two base exceptions are treated specially:
  503. If any task fails with <a class="reference internal" href="exceptions.html#KeyboardInterrupt" title="KeyboardInterrupt"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyboardInterrupt</span></code></a> or <a class="reference internal" href="exceptions.html#SystemExit" title="SystemExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemExit</span></code></a>,
  504. the task group still cancels the remaining tasks and waits for them,
  505. but then the initial <a class="reference internal" href="exceptions.html#KeyboardInterrupt" title="KeyboardInterrupt"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyboardInterrupt</span></code></a> or <a class="reference internal" href="exceptions.html#SystemExit" title="SystemExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemExit</span></code></a>
  506. is re-raised instead of <a class="reference internal" href="exceptions.html#ExceptionGroup" title="ExceptionGroup"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ExceptionGroup</span></code></a> or <a class="reference internal" href="exceptions.html#BaseExceptionGroup" title="BaseExceptionGroup"><code class="xref py py-exc docutils literal notranslate"><span class="pre">BaseExceptionGroup</span></code></a>.</p>
  507. <p>If the body of the <code class="docutils literal notranslate"><span class="pre">async</span> <span class="pre">with</span></code> statement exits with an exception
  508. (so <a class="reference internal" href="../reference/datamodel.html#object.__aexit__" title="object.__aexit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__aexit__()</span></code></a> is called with an exception set),
  509. this is treated the same as if one of the tasks failed:
  510. the remaining tasks are cancelled and then waited for,
  511. and non-cancellation exceptions are grouped into an
  512. exception group and raised.
  513. The exception passed into <a class="reference internal" href="../reference/datamodel.html#object.__aexit__" title="object.__aexit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__aexit__()</span></code></a>,
  514. unless it is <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">asyncio.CancelledError</span></code></a>,
  515. is also included in the exception group.
  516. The same special case is made for
  517. <a class="reference internal" href="exceptions.html#KeyboardInterrupt" title="KeyboardInterrupt"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyboardInterrupt</span></code></a> and <a class="reference internal" href="exceptions.html#SystemExit" title="SystemExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemExit</span></code></a> as in the previous paragraph.</p>
  518. </section>
  519. <section id="sleeping">
  520. <h2><a class="toc-backref" href="#id7" role="doc-backlink">Sleeping</a><a class="headerlink" href="#sleeping" title="Link to this heading">¶</a></h2>
  521. <dl class="py function">
  522. <dt class="sig sig-object py" id="asyncio.sleep">
  523. <em class="property"><span class="pre">coroutine</span> </em><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">sleep</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">delay</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">result</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.sleep" title="Link to this definition">¶</a></dt>
  524. <dd><p>Block for <em>delay</em> seconds.</p>
  525. <p>If <em>result</em> is provided, it is returned to the caller
  526. when the coroutine completes.</p>
  527. <p><code class="docutils literal notranslate"><span class="pre">sleep()</span></code> always suspends the current task, allowing other tasks
  528. to run.</p>
  529. <p>Setting the delay to 0 provides an optimized path to allow other
  530. tasks to run. This can be used by long-running functions to avoid
  531. blocking the event loop for the full duration of the function call.</p>
  532. <p id="asyncio-example-sleep">Example of coroutine displaying the current date every second
  533. for 5 seconds:</p>
  534. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">asyncio</span>
  535. <span class="kn">import</span> <span class="nn">datetime</span>
  536. <span class="k">async</span> <span class="k">def</span> <span class="nf">display_date</span><span class="p">():</span>
  537. <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>
  538. <span class="n">end_time</span> <span class="o">=</span> <span class="n">loop</span><span class="o">.</span><span class="n">time</span><span class="p">()</span> <span class="o">+</span> <span class="mf">5.0</span>
  539. <span class="k">while</span> <span class="kc">True</span><span class="p">:</span>
  540. <span class="nb">print</span><span class="p">(</span><span class="n">datetime</span><span class="o">.</span><span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">())</span>
  541. <span class="k">if</span> <span class="p">(</span><span class="n">loop</span><span class="o">.</span><span class="n">time</span><span class="p">()</span> <span class="o">+</span> <span class="mf">1.0</span><span class="p">)</span> <span class="o">&gt;=</span> <span class="n">end_time</span><span class="p">:</span>
  542. <span class="k">break</span>
  543. <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="mi">1</span><span class="p">)</span>
  544. <span class="n">asyncio</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="n">display_date</span><span class="p">())</span>
  545. </pre></div>
  546. </div>
  547. <div class="versionchanged">
  548. <p><span class="versionmodified changed">Changed in version 3.10: </span>Removed the <em>loop</em> parameter.</p>
  549. </div>
  550. </dd></dl>
  551. </section>
  552. <section id="running-tasks-concurrently">
  553. <h2><a class="toc-backref" href="#id8" role="doc-backlink">Running Tasks Concurrently</a><a class="headerlink" href="#running-tasks-concurrently" title="Link to this heading">¶</a></h2>
  554. <dl class="py function">
  555. <dt class="sig sig-object py" id="asyncio.gather">
  556. <em class="property"><span class="pre">awaitable</span> </em><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">gather</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="o"><span class="pre">*</span></span><span class="n"><span class="pre">aws</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">return_exceptions</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">False</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.gather" title="Link to this definition">¶</a></dt>
  557. <dd><p>Run <a class="reference internal" href="#asyncio-awaitables"><span class="std std-ref">awaitable objects</span></a> in the <em>aws</em>
  558. sequence <em>concurrently</em>.</p>
  559. <p>If any awaitable in <em>aws</em> is a coroutine, it is automatically
  560. scheduled as a Task.</p>
  561. <p>If all awaitables are completed successfully, the result is an
  562. aggregate list of returned values. The order of result values
  563. corresponds to the order of awaitables in <em>aws</em>.</p>
  564. <p>If <em>return_exceptions</em> is <code class="docutils literal notranslate"><span class="pre">False</span></code> (default), the first
  565. raised exception is immediately propagated to the task that
  566. awaits on <code class="docutils literal notranslate"><span class="pre">gather()</span></code>. Other awaitables in the <em>aws</em> sequence
  567. <strong>won’t be cancelled</strong> and will continue to run.</p>
  568. <p>If <em>return_exceptions</em> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, exceptions are treated the
  569. same as successful results, and aggregated in the result list.</p>
  570. <p>If <code class="docutils literal notranslate"><span class="pre">gather()</span></code> is <em>cancelled</em>, all submitted awaitables
  571. (that have not completed yet) are also <em>cancelled</em>.</p>
  572. <p>If any Task or Future from the <em>aws</em> sequence is <em>cancelled</em>, it is
  573. treated as if it raised <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> – the <code class="docutils literal notranslate"><span class="pre">gather()</span></code>
  574. call is <strong>not</strong> cancelled in this case. This is to prevent the
  575. cancellation of one submitted Task/Future to cause other
  576. Tasks/Futures to be cancelled.</p>
  577. <div class="admonition note">
  578. <p class="admonition-title">Note</p>
  579. <p>A new alternative to create and run tasks concurrently and
  580. wait for their completion is <a class="reference internal" href="#asyncio.TaskGroup" title="asyncio.TaskGroup"><code class="xref py py-class docutils literal notranslate"><span class="pre">asyncio.TaskGroup</span></code></a>. <em>TaskGroup</em>
  581. provides stronger safety guarantees than <em>gather</em> for scheduling a nesting of subtasks:
  582. if a task (or a subtask, a task scheduled by a task)
  583. raises an exception, <em>TaskGroup</em> will, while <em>gather</em> will not,
  584. cancel the remaining scheduled tasks).</p>
  585. </div>
  586. <p id="asyncio-example-gather">Example:</p>
  587. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">asyncio</span>
  588. <span class="k">async</span> <span class="k">def</span> <span class="nf">factorial</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">number</span><span class="p">):</span>
  589. <span class="n">f</span> <span class="o">=</span> <span class="mi">1</span>
  590. <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="n">number</span> <span class="o">+</span> <span class="mi">1</span><span class="p">):</span>
  591. <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">&quot;Task </span><span class="si">{</span><span class="n">name</span><span class="si">}</span><span class="s2">: Compute factorial(</span><span class="si">{</span><span class="n">number</span><span class="si">}</span><span class="s2">), currently i=</span><span class="si">{</span><span class="n">i</span><span class="si">}</span><span class="s2">...&quot;</span><span class="p">)</span>
  592. <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="mi">1</span><span class="p">)</span>
  593. <span class="n">f</span> <span class="o">*=</span> <span class="n">i</span>
  594. <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">&quot;Task </span><span class="si">{</span><span class="n">name</span><span class="si">}</span><span class="s2">: factorial(</span><span class="si">{</span><span class="n">number</span><span class="si">}</span><span class="s2">) = </span><span class="si">{</span><span class="n">f</span><span class="si">}</span><span class="s2">&quot;</span><span class="p">)</span>
  595. <span class="k">return</span> <span class="n">f</span>
  596. <span class="k">async</span> <span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
  597. <span class="c1"># Schedule three calls *concurrently*:</span>
  598. <span class="n">L</span> <span class="o">=</span> <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">gather</span><span class="p">(</span>
  599. <span class="n">factorial</span><span class="p">(</span><span class="s2">&quot;A&quot;</span><span class="p">,</span> <span class="mi">2</span><span class="p">),</span>
  600. <span class="n">factorial</span><span class="p">(</span><span class="s2">&quot;B&quot;</span><span class="p">,</span> <span class="mi">3</span><span class="p">),</span>
  601. <span class="n">factorial</span><span class="p">(</span><span class="s2">&quot;C&quot;</span><span class="p">,</span> <span class="mi">4</span><span class="p">),</span>
  602. <span class="p">)</span>
  603. <span class="nb">print</span><span class="p">(</span><span class="n">L</span><span class="p">)</span>
  604. <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>
  605. <span class="c1"># Expected output:</span>
  606. <span class="c1">#</span>
  607. <span class="c1"># Task A: Compute factorial(2), currently i=2...</span>
  608. <span class="c1"># Task B: Compute factorial(3), currently i=2...</span>
  609. <span class="c1"># Task C: Compute factorial(4), currently i=2...</span>
  610. <span class="c1"># Task A: factorial(2) = 2</span>
  611. <span class="c1"># Task B: Compute factorial(3), currently i=3...</span>
  612. <span class="c1"># Task C: Compute factorial(4), currently i=3...</span>
  613. <span class="c1"># Task B: factorial(3) = 6</span>
  614. <span class="c1"># Task C: Compute factorial(4), currently i=4...</span>
  615. <span class="c1"># Task C: factorial(4) = 24</span>
  616. <span class="c1"># [2, 6, 24]</span>
  617. </pre></div>
  618. </div>
  619. <div class="admonition note">
  620. <p class="admonition-title">Note</p>
  621. <p>If <em>return_exceptions</em> is False, cancelling gather() after it
  622. has been marked done won’t cancel any submitted awaitables.
  623. For instance, gather can be marked done after propagating an
  624. exception to the caller, therefore, calling <code class="docutils literal notranslate"><span class="pre">gather.cancel()</span></code>
  625. after catching an exception (raised by one of the awaitables) from
  626. gather won’t cancel any other awaitables.</p>
  627. </div>
  628. <div class="versionchanged">
  629. <p><span class="versionmodified changed">Changed in version 3.7: </span>If the <em>gather</em> itself is cancelled, the cancellation is
  630. propagated regardless of <em>return_exceptions</em>.</p>
  631. </div>
  632. <div class="versionchanged">
  633. <p><span class="versionmodified changed">Changed in version 3.10: </span>Removed the <em>loop</em> parameter.</p>
  634. </div>
  635. <div class="deprecated">
  636. <p><span class="versionmodified deprecated">Deprecated since version 3.10: </span>Deprecation warning is emitted if no positional arguments are provided
  637. or not all positional arguments are Future-like objects
  638. and there is no running event loop.</p>
  639. </div>
  640. </dd></dl>
  641. </section>
  642. <section id="eager-task-factory">
  643. <span id="id1"></span><h2><a class="toc-backref" href="#id9" role="doc-backlink">Eager Task Factory</a><a class="headerlink" href="#eager-task-factory" title="Link to this heading">¶</a></h2>
  644. <dl class="py function">
  645. <dt class="sig sig-object py" id="asyncio.eager_task_factory">
  646. <span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">eager_task_factory</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">loop</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">coro</span></span></em>, <em class="sig-param"><span class="o"><span class="pre">*</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">name</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></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.eager_task_factory" title="Link to this definition">¶</a></dt>
  647. <dd><p>A task factory for eager task execution.</p>
  648. <p>When using this factory (via <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.set_task_factory" title="asyncio.loop.set_task_factory"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.set_task_factory(asyncio.eager_task_factory)</span></code></a>),
  649. coroutines begin execution synchronously during <a class="reference internal" href="#asyncio.Task" title="asyncio.Task"><code class="xref py py-class docutils literal notranslate"><span class="pre">Task</span></code></a> construction.
  650. Tasks are only scheduled on the event loop if they block.
  651. This can be a performance improvement as the overhead of loop scheduling
  652. is avoided for coroutines that complete synchronously.</p>
  653. <p>A common example where this is beneficial is coroutines which employ
  654. caching or memoization to avoid actual I/O when possible.</p>
  655. <div class="admonition note">
  656. <p class="admonition-title">Note</p>
  657. <p>Immediate execution of the coroutine is a semantic change.
  658. If the coroutine returns or raises, the task is never scheduled
  659. to the event loop. If the coroutine execution blocks, the task is
  660. scheduled to the event loop. This change may introduce behavior
  661. changes to existing applications. For example,
  662. the application’s task execution order is likely to change.</p>
  663. </div>
  664. <div class="versionadded">
  665. <p><span class="versionmodified added">New in version 3.12.</span></p>
  666. </div>
  667. </dd></dl>
  668. <dl class="py function">
  669. <dt class="sig sig-object py" id="asyncio.create_eager_task_factory">
  670. <span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">create_eager_task_factory</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">custom_task_constructor</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.create_eager_task_factory" title="Link to this definition">¶</a></dt>
  671. <dd><p>Create an eager task factory, similar to <a class="reference internal" href="#asyncio.eager_task_factory" title="asyncio.eager_task_factory"><code class="xref py py-func docutils literal notranslate"><span class="pre">eager_task_factory()</span></code></a>,
  672. using the provided <em>custom_task_constructor</em> when creating a new task instead
  673. of the default <a class="reference internal" href="#asyncio.Task" title="asyncio.Task"><code class="xref py py-class docutils literal notranslate"><span class="pre">Task</span></code></a>.</p>
  674. <p><em>custom_task_constructor</em> must be a <em>callable</em> with the signature matching
  675. the signature of <a class="reference internal" href="#asyncio.Task" title="asyncio.Task"><code class="xref py py-class docutils literal notranslate"><span class="pre">Task.__init__</span></code></a>.
  676. The callable must return a <a class="reference internal" href="#asyncio.Task" title="asyncio.Task"><code class="xref py py-class docutils literal notranslate"><span class="pre">asyncio.Task</span></code></a>-compatible object.</p>
  677. <p>This function returns a <em>callable</em> intended to be used as a task factory of an
  678. event loop via <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.set_task_factory" title="asyncio.loop.set_task_factory"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.set_task_factory(factory)</span></code></a>).</p>
  679. <div class="versionadded">
  680. <p><span class="versionmodified added">New in version 3.12.</span></p>
  681. </div>
  682. </dd></dl>
  683. </section>
  684. <section id="shielding-from-cancellation">
  685. <h2><a class="toc-backref" href="#id10" role="doc-backlink">Shielding From Cancellation</a><a class="headerlink" href="#shielding-from-cancellation" title="Link to this heading">¶</a></h2>
  686. <dl class="py function">
  687. <dt class="sig sig-object py" id="asyncio.shield">
  688. <em class="property"><span class="pre">awaitable</span> </em><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">shield</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">aw</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.shield" title="Link to this definition">¶</a></dt>
  689. <dd><p>Protect an <a class="reference internal" href="#asyncio-awaitables"><span class="std std-ref">awaitable object</span></a>
  690. from being <a class="reference internal" href="#asyncio.Task.cancel" title="asyncio.Task.cancel"><code class="xref py py-meth docutils literal notranslate"><span class="pre">cancelled</span></code></a>.</p>
  691. <p>If <em>aw</em> is a coroutine it is automatically scheduled as a Task.</p>
  692. <p>The statement:</p>
  693. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">task</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">create_task</span><span class="p">(</span><span class="n">something</span><span class="p">())</span>
  694. <span class="n">res</span> <span class="o">=</span> <span class="k">await</span> <span class="n">shield</span><span class="p">(</span><span class="n">task</span><span class="p">)</span>
  695. </pre></div>
  696. </div>
  697. <p>is equivalent to:</p>
  698. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">res</span> <span class="o">=</span> <span class="k">await</span> <span class="n">something</span><span class="p">()</span>
  699. </pre></div>
  700. </div>
  701. <p><em>except</em> that if the coroutine containing it is cancelled, the
  702. Task running in <code class="docutils literal notranslate"><span class="pre">something()</span></code> is not cancelled. From the point
  703. of view of <code class="docutils literal notranslate"><span class="pre">something()</span></code>, the cancellation did not happen.
  704. Although its caller is still cancelled, so the “await” expression
  705. still raises a <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>.</p>
  706. <p>If <code class="docutils literal notranslate"><span class="pre">something()</span></code> is cancelled by other means (i.e. from within
  707. itself) that would also cancel <code class="docutils literal notranslate"><span class="pre">shield()</span></code>.</p>
  708. <p>If it is desired to completely ignore cancellation (not recommended)
  709. the <code class="docutils literal notranslate"><span class="pre">shield()</span></code> function should be combined with a try/except
  710. clause, as follows:</p>
  711. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">task</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">create_task</span><span class="p">(</span><span class="n">something</span><span class="p">())</span>
  712. <span class="k">try</span><span class="p">:</span>
  713. <span class="n">res</span> <span class="o">=</span> <span class="k">await</span> <span class="n">shield</span><span class="p">(</span><span class="n">task</span><span class="p">)</span>
  714. <span class="k">except</span> <span class="n">CancelledError</span><span class="p">:</span>
  715. <span class="n">res</span> <span class="o">=</span> <span class="kc">None</span>
  716. </pre></div>
  717. </div>
  718. <div class="admonition important">
  719. <p class="admonition-title">Important</p>
  720. <p>Save a reference to tasks passed to this function, to avoid
  721. a task disappearing mid-execution. The event loop only keeps
  722. weak references to tasks. A task that isn’t referenced elsewhere
  723. may get garbage collected at any time, even before it’s done.</p>
  724. </div>
  725. <div class="versionchanged">
  726. <p><span class="versionmodified changed">Changed in version 3.10: </span>Removed the <em>loop</em> parameter.</p>
  727. </div>
  728. <div class="deprecated">
  729. <p><span class="versionmodified deprecated">Deprecated since version 3.10: </span>Deprecation warning is emitted if <em>aw</em> is not Future-like object
  730. and there is no running event loop.</p>
  731. </div>
  732. </dd></dl>
  733. </section>
  734. <section id="timeouts">
  735. <h2><a class="toc-backref" href="#id11" role="doc-backlink">Timeouts</a><a class="headerlink" href="#timeouts" title="Link to this heading">¶</a></h2>
  736. <dl class="py function">
  737. <dt class="sig sig-object py" id="asyncio.timeout">
  738. <span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">timeout</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">delay</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.timeout" title="Link to this definition">¶</a></dt>
  739. <dd><p>Return an <a class="reference internal" href="../reference/datamodel.html#async-context-managers"><span class="std std-ref">asynchronous context manager</span></a>
  740. that can be used to limit the amount of time spent waiting on
  741. something.</p>
  742. <p><em>delay</em> can either be <code class="docutils literal notranslate"><span class="pre">None</span></code>, or a float/int number of
  743. seconds to wait. If <em>delay</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>, no time limit will
  744. be applied; this can be useful if the delay is unknown when
  745. the context manager is created.</p>
  746. <p>In either case, the context manager can be rescheduled after
  747. creation using <a class="reference internal" href="#asyncio.Timeout.reschedule" title="asyncio.Timeout.reschedule"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Timeout.reschedule()</span></code></a>.</p>
  748. <p>Example:</p>
  749. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">async</span> <span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
  750. <span class="k">async</span> <span class="k">with</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">timeout</span><span class="p">(</span><span class="mi">10</span><span class="p">):</span>
  751. <span class="k">await</span> <span class="n">long_running_task</span><span class="p">()</span>
  752. </pre></div>
  753. </div>
  754. <p>If <code class="docutils literal notranslate"><span class="pre">long_running_task</span></code> takes more than 10 seconds to complete,
  755. the context manager will cancel the current task and handle
  756. the resulting <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">asyncio.CancelledError</span></code></a> internally, transforming it
  757. into a <a class="reference internal" href="exceptions.html#TimeoutError" title="TimeoutError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TimeoutError</span></code></a> which can be caught and handled.</p>
  758. <div class="admonition note">
  759. <p class="admonition-title">Note</p>
  760. <p>The <a class="reference internal" href="#asyncio.timeout" title="asyncio.timeout"><code class="xref py py-func docutils literal notranslate"><span class="pre">asyncio.timeout()</span></code></a> context manager is what transforms
  761. the <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">asyncio.CancelledError</span></code></a> into a <a class="reference internal" href="exceptions.html#TimeoutError" title="TimeoutError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TimeoutError</span></code></a>,
  762. which means the <a class="reference internal" href="exceptions.html#TimeoutError" title="TimeoutError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TimeoutError</span></code></a> can only be caught
  763. <em>outside</em> of the context manager.</p>
  764. </div>
  765. <p>Example of catching <a class="reference internal" href="exceptions.html#TimeoutError" title="TimeoutError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TimeoutError</span></code></a>:</p>
  766. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">async</span> <span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
  767. <span class="k">try</span><span class="p">:</span>
  768. <span class="k">async</span> <span class="k">with</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">timeout</span><span class="p">(</span><span class="mi">10</span><span class="p">):</span>
  769. <span class="k">await</span> <span class="n">long_running_task</span><span class="p">()</span>
  770. <span class="k">except</span> <span class="ne">TimeoutError</span><span class="p">:</span>
  771. <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;The long operation timed out, but we&#39;ve handled it.&quot;</span><span class="p">)</span>
  772. <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;This statement will run regardless.&quot;</span><span class="p">)</span>
  773. </pre></div>
  774. </div>
  775. <p>The context manager produced by <a class="reference internal" href="#asyncio.timeout" title="asyncio.timeout"><code class="xref py py-func docutils literal notranslate"><span class="pre">asyncio.timeout()</span></code></a> can be
  776. rescheduled to a different deadline and inspected.</p>
  777. <dl class="py class">
  778. <dt class="sig sig-object py" id="asyncio.Timeout">
  779. <em class="property"><span class="pre">class</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">Timeout</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">when</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Timeout" title="Link to this definition">¶</a></dt>
  780. <dd><p>An <a class="reference internal" href="../reference/datamodel.html#async-context-managers"><span class="std std-ref">asynchronous context manager</span></a>
  781. for cancelling overdue coroutines.</p>
  782. <p><code class="docutils literal notranslate"><span class="pre">when</span></code> should be an absolute time at which the context should time out,
  783. as measured by the event loop’s clock:</p>
  784. <ul class="simple">
  785. <li><p>If <code class="docutils literal notranslate"><span class="pre">when</span></code> is <code class="docutils literal notranslate"><span class="pre">None</span></code>, the timeout will never trigger.</p></li>
  786. <li><p>If <code class="docutils literal notranslate"><span class="pre">when</span> <span class="pre">&lt;</span> <span class="pre">loop.time()</span></code>, the timeout will trigger on the next
  787. iteration of the event loop.</p></li>
  788. </ul>
  789. <blockquote>
  790. <div><dl class="py method">
  791. <dt class="sig sig-object py" id="asyncio.Timeout.when">
  792. <span class="sig-name descname"><span class="pre">when</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span> <span class="sig-return"><span class="sig-return-icon">&#x2192;</span> <span class="sig-return-typehint"><a class="reference internal" href="functions.html#float" title="float"><span class="pre">float</span></a><span class="w"> </span><span class="p"><span class="pre">|</span></span><span class="w"> </span><a class="reference internal" href="constants.html#None" title="None"><span class="pre">None</span></a></span></span><a class="headerlink" href="#asyncio.Timeout.when" title="Link to this definition">¶</a></dt>
  793. <dd><p>Return the current deadline, or <code class="docutils literal notranslate"><span class="pre">None</span></code> if the current
  794. deadline is not set.</p>
  795. </dd></dl>
  796. <dl class="py method">
  797. <dt class="sig sig-object py" id="asyncio.Timeout.reschedule">
  798. <span class="sig-name descname"><span class="pre">reschedule</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">when</span></span><span class="p"><span class="pre">:</span></span><span class="w"> </span><span class="n"><a class="reference internal" href="functions.html#float" title="float"><span class="pre">float</span></a><span class="w"> </span><span class="p"><span class="pre">|</span></span><span class="w"> </span><a class="reference internal" href="constants.html#None" title="None"><span class="pre">None</span></a></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Timeout.reschedule" title="Link to this definition">¶</a></dt>
  799. <dd><p>Reschedule the timeout.</p>
  800. </dd></dl>
  801. <dl class="py method">
  802. <dt class="sig sig-object py" id="asyncio.Timeout.expired">
  803. <span class="sig-name descname"><span class="pre">expired</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span> <span class="sig-return"><span class="sig-return-icon">&#x2192;</span> <span class="sig-return-typehint"><a class="reference internal" href="functions.html#bool" title="bool"><span class="pre">bool</span></a></span></span><a class="headerlink" href="#asyncio.Timeout.expired" title="Link to this definition">¶</a></dt>
  804. <dd><p>Return whether the context manager has exceeded its deadline
  805. (expired).</p>
  806. </dd></dl>
  807. </div></blockquote>
  808. </dd></dl>
  809. <p>Example:</p>
  810. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">async</span> <span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
  811. <span class="k">try</span><span class="p">:</span>
  812. <span class="c1"># We do not know the timeout when starting, so we pass ``None``.</span>
  813. <span class="k">async</span> <span class="k">with</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">timeout</span><span class="p">(</span><span class="kc">None</span><span class="p">)</span> <span class="k">as</span> <span class="n">cm</span><span class="p">:</span>
  814. <span class="c1"># We know the timeout now, so we reschedule it.</span>
  815. <span class="n">new_deadline</span> <span class="o">=</span> <span class="n">get_running_loop</span><span class="p">()</span><span class="o">.</span><span class="n">time</span><span class="p">()</span> <span class="o">+</span> <span class="mi">10</span>
  816. <span class="n">cm</span><span class="o">.</span><span class="n">reschedule</span><span class="p">(</span><span class="n">new_deadline</span><span class="p">)</span>
  817. <span class="k">await</span> <span class="n">long_running_task</span><span class="p">()</span>
  818. <span class="k">except</span> <span class="ne">TimeoutError</span><span class="p">:</span>
  819. <span class="k">pass</span>
  820. <span class="k">if</span> <span class="n">cm</span><span class="o">.</span><span class="n">expired</span><span class="p">():</span>
  821. <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Looks like we haven&#39;t finished on time.&quot;</span><span class="p">)</span>
  822. </pre></div>
  823. </div>
  824. <p>Timeout context managers can be safely nested.</p>
  825. <div class="versionadded">
  826. <p><span class="versionmodified added">New in version 3.11.</span></p>
  827. </div>
  828. </dd></dl>
  829. <dl class="py function">
  830. <dt class="sig sig-object py" id="asyncio.timeout_at">
  831. <span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">timeout_at</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">when</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.timeout_at" title="Link to this definition">¶</a></dt>
  832. <dd><p>Similar to <a class="reference internal" href="#asyncio.timeout" title="asyncio.timeout"><code class="xref py py-func docutils literal notranslate"><span class="pre">asyncio.timeout()</span></code></a>, except <em>when</em> is the absolute time
  833. to stop waiting, or <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
  834. <p>Example:</p>
  835. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">async</span> <span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
  836. <span class="n">loop</span> <span class="o">=</span> <span class="n">get_running_loop</span><span class="p">()</span>
  837. <span class="n">deadline</span> <span class="o">=</span> <span class="n">loop</span><span class="o">.</span><span class="n">time</span><span class="p">()</span> <span class="o">+</span> <span class="mi">20</span>
  838. <span class="k">try</span><span class="p">:</span>
  839. <span class="k">async</span> <span class="k">with</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">timeout_at</span><span class="p">(</span><span class="n">deadline</span><span class="p">):</span>
  840. <span class="k">await</span> <span class="n">long_running_task</span><span class="p">()</span>
  841. <span class="k">except</span> <span class="ne">TimeoutError</span><span class="p">:</span>
  842. <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;The long operation timed out, but we&#39;ve handled it.&quot;</span><span class="p">)</span>
  843. <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;This statement will run regardless.&quot;</span><span class="p">)</span>
  844. </pre></div>
  845. </div>
  846. <div class="versionadded">
  847. <p><span class="versionmodified added">New in version 3.11.</span></p>
  848. </div>
  849. </dd></dl>
  850. <dl class="py function">
  851. <dt class="sig sig-object py" id="asyncio.wait_for">
  852. <em class="property"><span class="pre">coroutine</span> </em><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">wait_for</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">aw</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">timeout</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.wait_for" title="Link to this definition">¶</a></dt>
  853. <dd><p>Wait for the <em>aw</em> <a class="reference internal" href="#asyncio-awaitables"><span class="std std-ref">awaitable</span></a>
  854. to complete with a timeout.</p>
  855. <p>If <em>aw</em> is a coroutine it is automatically scheduled as a Task.</p>
  856. <p><em>timeout</em> can either be <code class="docutils literal notranslate"><span class="pre">None</span></code> or a float or int number of seconds
  857. to wait for. If <em>timeout</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>, block until the future
  858. completes.</p>
  859. <p>If a timeout occurs, it cancels the task and raises
  860. <a class="reference internal" href="exceptions.html#TimeoutError" title="TimeoutError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TimeoutError</span></code></a>.</p>
  861. <p>To avoid the task <a class="reference internal" href="#asyncio.Task.cancel" title="asyncio.Task.cancel"><code class="xref py py-meth docutils literal notranslate"><span class="pre">cancellation</span></code></a>,
  862. wrap it in <a class="reference internal" href="#asyncio.shield" title="asyncio.shield"><code class="xref py py-func docutils literal notranslate"><span class="pre">shield()</span></code></a>.</p>
  863. <p>The function will wait until the future is actually cancelled,
  864. so the total wait time may exceed the <em>timeout</em>. If an exception
  865. happens during cancellation, it is propagated.</p>
  866. <p>If the wait is cancelled, the future <em>aw</em> is also cancelled.</p>
  867. <p id="asyncio-example-waitfor">Example:</p>
  868. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">async</span> <span class="k">def</span> <span class="nf">eternity</span><span class="p">():</span>
  869. <span class="c1"># Sleep for one hour</span>
  870. <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="mi">3600</span><span class="p">)</span>
  871. <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;yay!&#39;</span><span class="p">)</span>
  872. <span class="k">async</span> <span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
  873. <span class="c1"># Wait for at most 1 second</span>
  874. <span class="k">try</span><span class="p">:</span>
  875. <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">wait_for</span><span class="p">(</span><span class="n">eternity</span><span class="p">(),</span> <span class="n">timeout</span><span class="o">=</span><span class="mf">1.0</span><span class="p">)</span>
  876. <span class="k">except</span> <span class="ne">TimeoutError</span><span class="p">:</span>
  877. <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;timeout!&#39;</span><span class="p">)</span>
  878. <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>
  879. <span class="c1"># Expected output:</span>
  880. <span class="c1">#</span>
  881. <span class="c1"># timeout!</span>
  882. </pre></div>
  883. </div>
  884. <div class="versionchanged">
  885. <p><span class="versionmodified changed">Changed in version 3.7: </span>When <em>aw</em> is cancelled due to a timeout, <code class="docutils literal notranslate"><span class="pre">wait_for</span></code> waits
  886. for <em>aw</em> to be cancelled. Previously, it raised
  887. <a class="reference internal" href="exceptions.html#TimeoutError" title="TimeoutError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TimeoutError</span></code></a> immediately.</p>
  888. </div>
  889. <div class="versionchanged">
  890. <p><span class="versionmodified changed">Changed in version 3.10: </span>Removed the <em>loop</em> parameter.</p>
  891. </div>
  892. <div class="versionchanged">
  893. <p><span class="versionmodified changed">Changed in version 3.11: </span>Raises <a class="reference internal" href="exceptions.html#TimeoutError" title="TimeoutError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TimeoutError</span></code></a> instead of <a class="reference internal" href="asyncio-exceptions.html#asyncio.TimeoutError" title="asyncio.TimeoutError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">asyncio.TimeoutError</span></code></a>.</p>
  894. </div>
  895. </dd></dl>
  896. </section>
  897. <section id="waiting-primitives">
  898. <h2><a class="toc-backref" href="#id12" role="doc-backlink">Waiting Primitives</a><a class="headerlink" href="#waiting-primitives" title="Link to this heading">¶</a></h2>
  899. <dl class="py function">
  900. <dt class="sig sig-object py" id="asyncio.wait">
  901. <em class="property"><span class="pre">coroutine</span> </em><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">wait</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">aws</span></span></em>, <em class="sig-param"><span class="o"><span class="pre">*</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">timeout</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">return_when</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">ALL_COMPLETED</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.wait" title="Link to this definition">¶</a></dt>
  902. <dd><p>Run <a class="reference internal" href="asyncio-future.html#asyncio.Future" title="asyncio.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">Future</span></code></a> and <a class="reference internal" href="#asyncio.Task" title="asyncio.Task"><code class="xref py py-class docutils literal notranslate"><span class="pre">Task</span></code></a> instances in the <em>aws</em>
  903. iterable concurrently and block until the condition specified
  904. by <em>return_when</em>.</p>
  905. <p>The <em>aws</em> iterable must not be empty.</p>
  906. <p>Returns two sets of Tasks/Futures: <code class="docutils literal notranslate"><span class="pre">(done,</span> <span class="pre">pending)</span></code>.</p>
  907. <p>Usage:</p>
  908. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">done</span><span class="p">,</span> <span class="n">pending</span> <span class="o">=</span> <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">wait</span><span class="p">(</span><span class="n">aws</span><span class="p">)</span>
  909. </pre></div>
  910. </div>
  911. <p><em>timeout</em> (a float or int), if specified, can be used to control
  912. the maximum number of seconds to wait before returning.</p>
  913. <p>Note that this function does not raise <a class="reference internal" href="exceptions.html#TimeoutError" title="TimeoutError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TimeoutError</span></code></a>.
  914. Futures or Tasks that aren’t done when the timeout occurs are simply
  915. returned in the second set.</p>
  916. <p><em>return_when</em> indicates when this function should return. It must
  917. be one of the following constants:</p>
  918. <table class="docutils align-default">
  919. <thead>
  920. <tr class="row-odd"><th class="head"><p>Constant</p></th>
  921. <th class="head"><p>Description</p></th>
  922. </tr>
  923. </thead>
  924. <tbody>
  925. <tr class="row-even"><td><dl class="py data">
  926. <dt class="sig sig-object py" id="asyncio.FIRST_COMPLETED">
  927. <span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">FIRST_COMPLETED</span></span><a class="headerlink" href="#asyncio.FIRST_COMPLETED" title="Link to this definition">¶</a></dt>
  928. <dd></dd></dl>
  929. </td>
  930. <td><p>The function will return when any future finishes or is cancelled.</p></td>
  931. </tr>
  932. <tr class="row-odd"><td><dl class="py data">
  933. <dt class="sig sig-object py" id="asyncio.FIRST_EXCEPTION">
  934. <span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">FIRST_EXCEPTION</span></span><a class="headerlink" href="#asyncio.FIRST_EXCEPTION" title="Link to this definition">¶</a></dt>
  935. <dd></dd></dl>
  936. </td>
  937. <td><p>The function will return when any future finishes by raising an
  938. exception. If no future raises an exception
  939. then it is equivalent to <a class="reference internal" href="#asyncio.ALL_COMPLETED" title="asyncio.ALL_COMPLETED"><code class="xref py py-const docutils literal notranslate"><span class="pre">ALL_COMPLETED</span></code></a>.</p></td>
  940. </tr>
  941. <tr class="row-even"><td><dl class="py data">
  942. <dt class="sig sig-object py" id="asyncio.ALL_COMPLETED">
  943. <span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">ALL_COMPLETED</span></span><a class="headerlink" href="#asyncio.ALL_COMPLETED" title="Link to this definition">¶</a></dt>
  944. <dd></dd></dl>
  945. </td>
  946. <td><p>The function will return when all futures finish or are cancelled.</p></td>
  947. </tr>
  948. </tbody>
  949. </table>
  950. <p>Unlike <a class="reference internal" href="#asyncio.wait_for" title="asyncio.wait_for"><code class="xref py py-func docutils literal notranslate"><span class="pre">wait_for()</span></code></a>, <code class="docutils literal notranslate"><span class="pre">wait()</span></code> does not cancel the
  951. futures when a timeout occurs.</p>
  952. <div class="versionchanged">
  953. <p><span class="versionmodified changed">Changed in version 3.10: </span>Removed the <em>loop</em> parameter.</p>
  954. </div>
  955. <div class="versionchanged">
  956. <p><span class="versionmodified changed">Changed in version 3.11: </span>Passing coroutine objects to <code class="docutils literal notranslate"><span class="pre">wait()</span></code> directly is forbidden.</p>
  957. </div>
  958. <div class="versionchanged">
  959. <p><span class="versionmodified changed">Changed in version 3.12: </span>Added support for generators yielding tasks.</p>
  960. </div>
  961. </dd></dl>
  962. <dl class="py function">
  963. <dt class="sig sig-object py" id="asyncio.as_completed">
  964. <span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">as_completed</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">aws</span></span></em>, <em class="sig-param"><span class="o"><span class="pre">*</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">timeout</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.as_completed" title="Link to this definition">¶</a></dt>
  965. <dd><p>Run <a class="reference internal" href="#asyncio-awaitables"><span class="std std-ref">awaitable objects</span></a> in the <em>aws</em>
  966. iterable concurrently. Return an iterator of coroutines.
  967. Each coroutine returned can be awaited to get the earliest next
  968. result from the iterable of the remaining awaitables.</p>
  969. <p>Raises <a class="reference internal" href="exceptions.html#TimeoutError" title="TimeoutError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TimeoutError</span></code></a> if the timeout occurs before
  970. all Futures are done.</p>
  971. <p>Example:</p>
  972. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">coro</span> <span class="ow">in</span> <span class="n">as_completed</span><span class="p">(</span><span class="n">aws</span><span class="p">):</span>
  973. <span class="n">earliest_result</span> <span class="o">=</span> <span class="k">await</span> <span class="n">coro</span>
  974. <span class="c1"># ...</span>
  975. </pre></div>
  976. </div>
  977. <div class="versionchanged">
  978. <p><span class="versionmodified changed">Changed in version 3.10: </span>Removed the <em>loop</em> parameter.</p>
  979. </div>
  980. <div class="deprecated">
  981. <p><span class="versionmodified deprecated">Deprecated since version 3.10: </span>Deprecation warning is emitted if not all awaitable objects in the <em>aws</em>
  982. iterable are Future-like objects and there is no running event loop.</p>
  983. </div>
  984. <div class="versionchanged">
  985. <p><span class="versionmodified changed">Changed in version 3.12: </span>Added support for generators yielding tasks.</p>
  986. </div>
  987. </dd></dl>
  988. </section>
  989. <section id="running-in-threads">
  990. <h2><a class="toc-backref" href="#id13" role="doc-backlink">Running in Threads</a><a class="headerlink" href="#running-in-threads" title="Link to this heading">¶</a></h2>
  991. <dl class="py function">
  992. <dt class="sig sig-object py" id="asyncio.to_thread">
  993. <em class="property"><span class="pre">coroutine</span> </em><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">to_thread</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">func</span></span></em>, <em class="sig-param"><span class="o"><span class="pre">/</span></span></em>, <em class="sig-param"><span class="o"><span class="pre">*</span></span><span class="n"><span class="pre">args</span></span></em>, <em class="sig-param"><span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">kwargs</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.to_thread" title="Link to this definition">¶</a></dt>
  994. <dd><p>Asynchronously run function <em>func</em> in a separate thread.</p>
  995. <p>Any *args and **kwargs supplied for this function are directly passed
  996. to <em>func</em>. Also, the current <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> is propagated,
  997. allowing context variables from the event loop thread to be accessed in the
  998. separate thread.</p>
  999. <p>Return a coroutine that can be awaited to get the eventual result of <em>func</em>.</p>
  1000. <p>This coroutine function is primarily intended to be used for executing
  1001. IO-bound functions/methods that would otherwise block the event loop if
  1002. they were run in the main thread. For example:</p>
  1003. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">blocking_io</span><span class="p">():</span>
  1004. <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">&quot;start blocking_io at </span><span class="si">{</span><span class="n">time</span><span class="o">.</span><span class="n">strftime</span><span class="p">(</span><span class="s1">&#39;</span><span class="si">%X</span><span class="s1">&#39;</span><span class="p">)</span><span class="si">}</span><span class="s2">&quot;</span><span class="p">)</span>
  1005. <span class="c1"># Note that time.sleep() can be replaced with any blocking</span>
  1006. <span class="c1"># IO-bound operation, such as file operations.</span>
  1007. <span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
  1008. <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">&quot;blocking_io complete at </span><span class="si">{</span><span class="n">time</span><span class="o">.</span><span class="n">strftime</span><span class="p">(</span><span class="s1">&#39;</span><span class="si">%X</span><span class="s1">&#39;</span><span class="p">)</span><span class="si">}</span><span class="s2">&quot;</span><span class="p">)</span>
  1009. <span class="k">async</span> <span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
  1010. <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">&quot;started main at </span><span class="si">{</span><span class="n">time</span><span class="o">.</span><span class="n">strftime</span><span class="p">(</span><span class="s1">&#39;</span><span class="si">%X</span><span class="s1">&#39;</span><span class="p">)</span><span class="si">}</span><span class="s2">&quot;</span><span class="p">)</span>
  1011. <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">gather</span><span class="p">(</span>
  1012. <span class="n">asyncio</span><span class="o">.</span><span class="n">to_thread</span><span class="p">(</span><span class="n">blocking_io</span><span class="p">),</span>
  1013. <span class="n">asyncio</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mi">1</span><span class="p">))</span>
  1014. <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">&quot;finished main at </span><span class="si">{</span><span class="n">time</span><span class="o">.</span><span class="n">strftime</span><span class="p">(</span><span class="s1">&#39;</span><span class="si">%X</span><span class="s1">&#39;</span><span class="p">)</span><span class="si">}</span><span class="s2">&quot;</span><span class="p">)</span>
  1015. <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>
  1016. <span class="c1"># Expected output:</span>
  1017. <span class="c1">#</span>
  1018. <span class="c1"># started main at 19:50:53</span>
  1019. <span class="c1"># start blocking_io at 19:50:53</span>
  1020. <span class="c1"># blocking_io complete at 19:50:54</span>
  1021. <span class="c1"># finished main at 19:50:54</span>
  1022. </pre></div>
  1023. </div>
  1024. <p>Directly calling <code class="docutils literal notranslate"><span class="pre">blocking_io()</span></code> in any coroutine would block the event loop
  1025. for its duration, resulting in an additional 1 second of run time. Instead,
  1026. by using <code class="docutils literal notranslate"><span class="pre">asyncio.to_thread()</span></code>, we can run it in a separate thread without
  1027. blocking the event loop.</p>
  1028. <div class="admonition note">
  1029. <p class="admonition-title">Note</p>
  1030. <p>Due to the <a class="reference internal" href="../glossary.html#term-GIL"><span class="xref std std-term">GIL</span></a>, <code class="docutils literal notranslate"><span class="pre">asyncio.to_thread()</span></code> can typically only be used
  1031. to make IO-bound functions non-blocking. However, for extension modules
  1032. that release the GIL or alternative Python implementations that don’t
  1033. have one, <code class="docutils literal notranslate"><span class="pre">asyncio.to_thread()</span></code> can also be used for CPU-bound functions.</p>
  1034. </div>
  1035. <div class="versionadded">
  1036. <p><span class="versionmodified added">New in version 3.9.</span></p>
  1037. </div>
  1038. </dd></dl>
  1039. </section>
  1040. <section id="scheduling-from-other-threads">
  1041. <h2><a class="toc-backref" href="#id14" role="doc-backlink">Scheduling From Other Threads</a><a class="headerlink" href="#scheduling-from-other-threads" title="Link to this heading">¶</a></h2>
  1042. <dl class="py function">
  1043. <dt class="sig sig-object py" id="asyncio.run_coroutine_threadsafe">
  1044. <span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">run_coroutine_threadsafe</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">coro</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">loop</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.run_coroutine_threadsafe" title="Link to this definition">¶</a></dt>
  1045. <dd><p>Submit a coroutine to the given event loop. Thread-safe.</p>
  1046. <p>Return 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> to wait for the result
  1047. from another OS thread.</p>
  1048. <p>This function is meant to be called from a different OS thread
  1049. than the one where the event loop is running. Example:</p>
  1050. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># Create a coroutine</span>
  1051. <span class="n">coro</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="n">result</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span>
  1052. <span class="c1"># Submit the coroutine to a given loop</span>
  1053. <span class="n">future</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">run_coroutine_threadsafe</span><span class="p">(</span><span class="n">coro</span><span class="p">,</span> <span class="n">loop</span><span class="p">)</span>
  1054. <span class="c1"># Wait for the result with an optional timeout argument</span>
  1055. <span class="k">assert</span> <span class="n">future</span><span class="o">.</span><span class="n">result</span><span class="p">(</span><span class="n">timeout</span><span class="p">)</span> <span class="o">==</span> <span class="mi">3</span>
  1056. </pre></div>
  1057. </div>
  1058. <p>If an exception is raised in the coroutine, the returned Future
  1059. will be notified. It can also be used to cancel the task in
  1060. the event loop:</p>
  1061. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span>
  1062. <span class="n">result</span> <span class="o">=</span> <span class="n">future</span><span class="o">.</span><span class="n">result</span><span class="p">(</span><span class="n">timeout</span><span class="p">)</span>
  1063. <span class="k">except</span> <span class="ne">TimeoutError</span><span class="p">:</span>
  1064. <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;The coroutine took too long, cancelling the task...&#39;</span><span class="p">)</span>
  1065. <span class="n">future</span><span class="o">.</span><span class="n">cancel</span><span class="p">()</span>
  1066. <span class="k">except</span> <span class="ne">Exception</span> <span class="k">as</span> <span class="n">exc</span><span class="p">:</span>
  1067. <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;The coroutine raised an exception: </span><span class="si">{</span><span class="n">exc</span><span class="si">!r}</span><span class="s1">&#39;</span><span class="p">)</span>
  1068. <span class="k">else</span><span class="p">:</span>
  1069. <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;The coroutine returned: </span><span class="si">{</span><span class="n">result</span><span class="si">!r}</span><span class="s1">&#39;</span><span class="p">)</span>
  1070. </pre></div>
  1071. </div>
  1072. <p>See the <a class="reference internal" href="asyncio-dev.html#asyncio-multithreading"><span class="std std-ref">concurrency and multithreading</span></a>
  1073. section of the documentation.</p>
  1074. <p>Unlike other asyncio functions this function requires the <em>loop</em>
  1075. argument to be passed explicitly.</p>
  1076. <div class="versionadded">
  1077. <p><span class="versionmodified added">New in version 3.5.1.</span></p>
  1078. </div>
  1079. </dd></dl>
  1080. </section>
  1081. <section id="introspection">
  1082. <h2><a class="toc-backref" href="#id15" role="doc-backlink">Introspection</a><a class="headerlink" href="#introspection" title="Link to this heading">¶</a></h2>
  1083. <dl class="py function">
  1084. <dt class="sig sig-object py" id="asyncio.current_task">
  1085. <span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">current_task</span></span><span class="sig-paren">(</span><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.current_task" title="Link to this definition">¶</a></dt>
  1086. <dd><p>Return the currently running <a class="reference internal" href="#asyncio.Task" title="asyncio.Task"><code class="xref py py-class docutils literal notranslate"><span class="pre">Task</span></code></a> instance, or <code class="docutils literal notranslate"><span class="pre">None</span></code> if
  1087. no task is running.</p>
  1088. <p>If <em>loop</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code> <a class="reference internal" href="asyncio-eventloop.html#asyncio.get_running_loop" title="asyncio.get_running_loop"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_running_loop()</span></code></a> is used to get
  1089. the current loop.</p>
  1090. <div class="versionadded">
  1091. <p><span class="versionmodified added">New in version 3.7.</span></p>
  1092. </div>
  1093. </dd></dl>
  1094. <dl class="py function">
  1095. <dt class="sig sig-object py" id="asyncio.all_tasks">
  1096. <span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">all_tasks</span></span><span class="sig-paren">(</span><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.all_tasks" title="Link to this definition">¶</a></dt>
  1097. <dd><p>Return a set of not yet finished <a class="reference internal" href="#asyncio.Task" title="asyncio.Task"><code class="xref py py-class docutils literal notranslate"><span class="pre">Task</span></code></a> objects run by
  1098. the loop.</p>
  1099. <p>If <em>loop</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>, <a class="reference internal" href="asyncio-eventloop.html#asyncio.get_running_loop" title="asyncio.get_running_loop"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_running_loop()</span></code></a> is used for getting
  1100. current loop.</p>
  1101. <div class="versionadded">
  1102. <p><span class="versionmodified added">New in version 3.7.</span></p>
  1103. </div>
  1104. </dd></dl>
  1105. <dl class="py function">
  1106. <dt class="sig sig-object py" id="asyncio.iscoroutine">
  1107. <span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">iscoroutine</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.iscoroutine" title="Link to this definition">¶</a></dt>
  1108. <dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if <em>obj</em> is a coroutine object.</p>
  1109. <div class="versionadded">
  1110. <p><span class="versionmodified added">New in version 3.4.</span></p>
  1111. </div>
  1112. </dd></dl>
  1113. </section>
  1114. <section id="task-object">
  1115. <h2><a class="toc-backref" href="#id16" role="doc-backlink">Task Object</a><a class="headerlink" href="#task-object" title="Link to this heading">¶</a></h2>
  1116. <dl class="py class">
  1117. <dt class="sig sig-object py" id="asyncio.Task">
  1118. <em class="property"><span class="pre">class</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">Task</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">coro</span></span></em>, <em class="sig-param"><span class="o"><span class="pre">*</span></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>, <em class="sig-param"><span class="n"><span class="pre">name</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></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>, <em class="sig-param"><span class="n"><span class="pre">eager_start</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">False</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Task" title="Link to this definition">¶</a></dt>
  1119. <dd><p>A <a class="reference internal" href="asyncio-future.html#asyncio.Future" title="asyncio.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">Future-like</span></code></a> object that runs a Python
  1120. <a class="reference internal" href="#coroutine"><span class="std std-ref">coroutine</span></a>. Not thread-safe.</p>
  1121. <p>Tasks are used to run coroutines in event loops.
  1122. If a coroutine awaits on a Future, the Task suspends
  1123. the execution of the coroutine and waits for the completion
  1124. of the Future. When the Future is <em>done</em>, the execution of
  1125. the wrapped coroutine resumes.</p>
  1126. <p>Event loops use cooperative scheduling: an event loop runs
  1127. one Task at a time. While a Task awaits for the completion of a
  1128. Future, the event loop runs other Tasks, callbacks, or performs
  1129. IO operations.</p>
  1130. <p>Use the high-level <a class="reference internal" href="#asyncio.create_task" title="asyncio.create_task"><code class="xref py py-func docutils literal notranslate"><span class="pre">asyncio.create_task()</span></code></a> function to create
  1131. Tasks, or the low-level <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.create_task" title="asyncio.loop.create_task"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.create_task()</span></code></a> or
  1132. <a class="reference internal" href="asyncio-future.html#asyncio.ensure_future" title="asyncio.ensure_future"><code class="xref py py-func docutils literal notranslate"><span class="pre">ensure_future()</span></code></a> functions. Manual instantiation of Tasks
  1133. is discouraged.</p>
  1134. <p>To cancel a running Task use the <a class="reference internal" href="#asyncio.Task.cancel" title="asyncio.Task.cancel"><code class="xref py py-meth docutils literal notranslate"><span class="pre">cancel()</span></code></a> method. Calling it
  1135. will cause the Task to throw a <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 into
  1136. the wrapped coroutine. If a coroutine is awaiting on a Future
  1137. object during cancellation, the Future object will be cancelled.</p>
  1138. <p><a class="reference internal" href="#asyncio.Task.cancelled" title="asyncio.Task.cancelled"><code class="xref py py-meth docutils literal notranslate"><span class="pre">cancelled()</span></code></a> can be used to check if the Task was cancelled.
  1139. The method returns <code class="docutils literal notranslate"><span class="pre">True</span></code> if the wrapped coroutine did not
  1140. suppress the <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 and was actually
  1141. cancelled.</p>
  1142. <p><a class="reference internal" href="#asyncio.Task" title="asyncio.Task"><code class="xref py py-class docutils literal notranslate"><span class="pre">asyncio.Task</span></code></a> inherits from <a class="reference internal" href="asyncio-future.html#asyncio.Future" title="asyncio.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">Future</span></code></a> all of its
  1143. APIs except <a class="reference internal" href="asyncio-future.html#asyncio.Future.set_result" title="asyncio.Future.set_result"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Future.set_result()</span></code></a> and
  1144. <a class="reference internal" href="asyncio-future.html#asyncio.Future.set_exception" title="asyncio.Future.set_exception"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Future.set_exception()</span></code></a>.</p>
  1145. <p>An optional keyword-only <em>context</em> argument allows specifying a
  1146. custom <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>coro</em> to run in.
  1147. If no <em>context</em> is provided, the Task copies the current context
  1148. and later runs its coroutine in the copied context.</p>
  1149. <p>An optional keyword-only <em>eager_start</em> argument allows eagerly starting
  1150. the execution of the <a class="reference internal" href="#asyncio.Task" title="asyncio.Task"><code class="xref py py-class docutils literal notranslate"><span class="pre">asyncio.Task</span></code></a> at task creation time.
  1151. If set to <code class="docutils literal notranslate"><span class="pre">True</span></code> and the event loop is running, the task will start
  1152. executing the coroutine immediately, until the first time the coroutine
  1153. blocks. If the coroutine returns or raises without blocking, the task
  1154. will be finished eagerly and will skip scheduling to the event loop.</p>
  1155. <div class="versionchanged">
  1156. <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>
  1157. </div>
  1158. <div class="versionchanged">
  1159. <p><span class="versionmodified changed">Changed in version 3.8: </span>Added the <em>name</em> parameter.</p>
  1160. </div>
  1161. <div class="deprecated">
  1162. <p><span class="versionmodified deprecated">Deprecated since version 3.10: </span>Deprecation warning is emitted if <em>loop</em> is not specified
  1163. and there is no running event loop.</p>
  1164. </div>
  1165. <div class="versionchanged">
  1166. <p><span class="versionmodified changed">Changed in version 3.11: </span>Added the <em>context</em> parameter.</p>
  1167. </div>
  1168. <div class="versionchanged">
  1169. <p><span class="versionmodified changed">Changed in version 3.12: </span>Added the <em>eager_start</em> parameter.</p>
  1170. </div>
  1171. <dl class="py method">
  1172. <dt class="sig sig-object py" id="asyncio.Task.done">
  1173. <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.Task.done" title="Link to this definition">¶</a></dt>
  1174. <dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the Task is <em>done</em>.</p>
  1175. <p>A Task is <em>done</em> when the wrapped coroutine either returned
  1176. a value, raised an exception, or the Task was cancelled.</p>
  1177. </dd></dl>
  1178. <dl class="py method">
  1179. <dt class="sig sig-object py" id="asyncio.Task.result">
  1180. <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.Task.result" title="Link to this definition">¶</a></dt>
  1181. <dd><p>Return the result of the Task.</p>
  1182. <p>If the Task is <em>done</em>, the result of the wrapped coroutine
  1183. is returned (or if the coroutine raised an exception, that
  1184. exception is re-raised.)</p>
  1185. <p>If the Task has been <em>cancelled</em>, this method raises
  1186. a <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>
  1187. <p>If the Task’s result isn’t yet available, this method raises
  1188. a <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>
  1189. </dd></dl>
  1190. <dl class="py method">
  1191. <dt class="sig sig-object py" id="asyncio.Task.exception">
  1192. <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.Task.exception" title="Link to this definition">¶</a></dt>
  1193. <dd><p>Return the exception of the Task.</p>
  1194. <p>If the wrapped coroutine raised an exception that exception
  1195. is returned. If the wrapped coroutine returned normally
  1196. this method returns <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
  1197. <p>If the Task has been <em>cancelled</em>, this method raises a
  1198. <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>
  1199. <p>If the Task isn’t <em>done</em> yet, this method raises an
  1200. <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>
  1201. </dd></dl>
  1202. <dl class="py method">
  1203. <dt class="sig sig-object py" id="asyncio.Task.add_done_callback">
  1204. <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="o"><span class="pre">*</span></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.Task.add_done_callback" title="Link to this definition">¶</a></dt>
  1205. <dd><p>Add a callback to be run when the Task is <em>done</em>.</p>
  1206. <p>This method should only be used in low-level callback-based code.</p>
  1207. <p>See the documentation of <a class="reference internal" href="asyncio-future.html#asyncio.Future.add_done_callback" title="asyncio.Future.add_done_callback"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Future.add_done_callback()</span></code></a>
  1208. for more details.</p>
  1209. </dd></dl>
  1210. <dl class="py method">
  1211. <dt class="sig sig-object py" id="asyncio.Task.remove_done_callback">
  1212. <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.Task.remove_done_callback" title="Link to this definition">¶</a></dt>
  1213. <dd><p>Remove <em>callback</em> from the callbacks list.</p>
  1214. <p>This method should only be used in low-level callback-based code.</p>
  1215. <p>See the documentation of <a class="reference internal" href="asyncio-future.html#asyncio.Future.remove_done_callback" title="asyncio.Future.remove_done_callback"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Future.remove_done_callback()</span></code></a>
  1216. for more details.</p>
  1217. </dd></dl>
  1218. <dl class="py method">
  1219. <dt class="sig sig-object py" id="asyncio.Task.get_stack">
  1220. <span class="sig-name descname"><span class="pre">get_stack</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="o"><span class="pre">*</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">limit</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.Task.get_stack" title="Link to this definition">¶</a></dt>
  1221. <dd><p>Return the list of stack frames for this Task.</p>
  1222. <p>If the wrapped coroutine is not done, this returns the stack
  1223. where it is suspended. If the coroutine has completed
  1224. successfully or was cancelled, this returns an empty list.
  1225. If the coroutine was terminated by an exception, this returns
  1226. the list of traceback frames.</p>
  1227. <p>The frames are always ordered from oldest to newest.</p>
  1228. <p>Only one stack frame is returned for a suspended coroutine.</p>
  1229. <p>The optional <em>limit</em> argument sets the maximum number of frames
  1230. to return; by default all available frames are returned.
  1231. The ordering of the returned list differs depending on whether
  1232. a stack or a traceback is returned: the newest frames of a
  1233. stack are returned, but the oldest frames of a traceback are
  1234. returned. (This matches the behavior of the traceback module.)</p>
  1235. </dd></dl>
  1236. <dl class="py method">
  1237. <dt class="sig sig-object py" id="asyncio.Task.print_stack">
  1238. <span class="sig-name descname"><span class="pre">print_stack</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="o"><span class="pre">*</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">limit</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">file</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.Task.print_stack" title="Link to this definition">¶</a></dt>
  1239. <dd><p>Print the stack or traceback for this Task.</p>
  1240. <p>This produces output similar to that of the traceback module
  1241. for the frames retrieved by <a class="reference internal" href="#asyncio.Task.get_stack" title="asyncio.Task.get_stack"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_stack()</span></code></a>.</p>
  1242. <p>The <em>limit</em> argument is passed to <a class="reference internal" href="#asyncio.Task.get_stack" title="asyncio.Task.get_stack"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_stack()</span></code></a> directly.</p>
  1243. <p>The <em>file</em> argument is an I/O stream to which the output
  1244. is written; by default output is written to <a class="reference internal" href="sys.html#sys.stdout" title="sys.stdout"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.stdout</span></code></a>.</p>
  1245. </dd></dl>
  1246. <dl class="py method">
  1247. <dt class="sig sig-object py" id="asyncio.Task.get_coro">
  1248. <span class="sig-name descname"><span class="pre">get_coro</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Task.get_coro" title="Link to this definition">¶</a></dt>
  1249. <dd><p>Return the coroutine object wrapped by the <a class="reference internal" href="#asyncio.Task" title="asyncio.Task"><code class="xref py py-class docutils literal notranslate"><span class="pre">Task</span></code></a>.</p>
  1250. <div class="admonition note">
  1251. <p class="admonition-title">Note</p>
  1252. <p>This will return <code class="docutils literal notranslate"><span class="pre">None</span></code> for Tasks which have already
  1253. completed eagerly. See the <a class="reference internal" href="#eager-task-factory"><span class="std std-ref">Eager Task Factory</span></a>.</p>
  1254. </div>
  1255. <div class="versionadded">
  1256. <p><span class="versionmodified added">New in version 3.8.</span></p>
  1257. </div>
  1258. <div class="versionchanged">
  1259. <p><span class="versionmodified changed">Changed in version 3.12: </span>Newly added eager task execution means result may be <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
  1260. </div>
  1261. </dd></dl>
  1262. <dl class="py method">
  1263. <dt class="sig sig-object py" id="asyncio.Task.get_context">
  1264. <span class="sig-name descname"><span class="pre">get_context</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Task.get_context" title="Link to this definition">¶</a></dt>
  1265. <dd><p>Return the <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> object
  1266. associated with the task.</p>
  1267. <div class="versionadded">
  1268. <p><span class="versionmodified added">New in version 3.12.</span></p>
  1269. </div>
  1270. </dd></dl>
  1271. <dl class="py method">
  1272. <dt class="sig sig-object py" id="asyncio.Task.get_name">
  1273. <span class="sig-name descname"><span class="pre">get_name</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Task.get_name" title="Link to this definition">¶</a></dt>
  1274. <dd><p>Return the name of the Task.</p>
  1275. <p>If no name has been explicitly assigned to the Task, the default
  1276. asyncio Task implementation generates a default name during
  1277. instantiation.</p>
  1278. <div class="versionadded">
  1279. <p><span class="versionmodified added">New in version 3.8.</span></p>
  1280. </div>
  1281. </dd></dl>
  1282. <dl class="py method">
  1283. <dt class="sig sig-object py" id="asyncio.Task.set_name">
  1284. <span class="sig-name descname"><span class="pre">set_name</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">value</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Task.set_name" title="Link to this definition">¶</a></dt>
  1285. <dd><p>Set the name of the Task.</p>
  1286. <p>The <em>value</em> argument can be any object, which is then
  1287. converted to a string.</p>
  1288. <p>In the default Task implementation, the name will be visible
  1289. in the <a class="reference internal" href="functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a> output of a task object.</p>
  1290. <div class="versionadded">
  1291. <p><span class="versionmodified added">New in version 3.8.</span></p>
  1292. </div>
  1293. </dd></dl>
  1294. <dl class="py method">
  1295. <dt class="sig sig-object py" id="asyncio.Task.cancel">
  1296. <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.Task.cancel" title="Link to this definition">¶</a></dt>
  1297. <dd><p>Request the Task to be cancelled.</p>
  1298. <p>This arranges for a <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 to be thrown
  1299. into the wrapped coroutine on the next cycle of the event loop.</p>
  1300. <p>The coroutine then has a chance to clean up or even deny the
  1301. request by suppressing the exception with a <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> …
  1302. … <code class="docutils literal notranslate"><span class="pre">except</span> <span class="pre">CancelledError</span></code> … <a class="reference internal" href="../reference/compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> block.
  1303. Therefore, unlike <a class="reference internal" href="asyncio-future.html#asyncio.Future.cancel" title="asyncio.Future.cancel"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Future.cancel()</span></code></a>, <a class="reference internal" href="#asyncio.Task.cancel" title="asyncio.Task.cancel"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Task.cancel()</span></code></a> does
  1304. not guarantee that the Task will be cancelled, although
  1305. suppressing cancellation completely is not common and is actively
  1306. discouraged. Should the coroutine nevertheless decide to suppress
  1307. the cancellation, it needs to call <a class="reference internal" href="#asyncio.Task.uncancel" title="asyncio.Task.uncancel"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Task.uncancel()</span></code></a> in addition
  1308. to catching the exception.</p>
  1309. <div class="versionchanged">
  1310. <p><span class="versionmodified changed">Changed in version 3.9: </span>Added the <em>msg</em> parameter.</p>
  1311. </div>
  1312. <div class="versionchanged">
  1313. <p><span class="versionmodified changed">Changed in version 3.11: </span>The <code class="docutils literal notranslate"><span class="pre">msg</span></code> parameter is propagated from cancelled task to its awaiter.</p>
  1314. </div>
  1315. <p id="asyncio-example-task-cancel">The following example illustrates how coroutines can intercept
  1316. the cancellation request:</p>
  1317. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">async</span> <span class="k">def</span> <span class="nf">cancel_me</span><span class="p">():</span>
  1318. <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;cancel_me(): before sleep&#39;</span><span class="p">)</span>
  1319. <span class="k">try</span><span class="p">:</span>
  1320. <span class="c1"># Wait for 1 hour</span>
  1321. <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="mi">3600</span><span class="p">)</span>
  1322. <span class="k">except</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">CancelledError</span><span class="p">:</span>
  1323. <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;cancel_me(): cancel sleep&#39;</span><span class="p">)</span>
  1324. <span class="k">raise</span>
  1325. <span class="k">finally</span><span class="p">:</span>
  1326. <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;cancel_me(): after sleep&#39;</span><span class="p">)</span>
  1327. <span class="k">async</span> <span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
  1328. <span class="c1"># Create a &quot;cancel_me&quot; Task</span>
  1329. <span class="n">task</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">create_task</span><span class="p">(</span><span class="n">cancel_me</span><span class="p">())</span>
  1330. <span class="c1"># Wait for 1 second</span>
  1331. <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="mi">1</span><span class="p">)</span>
  1332. <span class="n">task</span><span class="o">.</span><span class="n">cancel</span><span class="p">()</span>
  1333. <span class="k">try</span><span class="p">:</span>
  1334. <span class="k">await</span> <span class="n">task</span>
  1335. <span class="k">except</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">CancelledError</span><span class="p">:</span>
  1336. <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;main(): cancel_me is cancelled now&quot;</span><span class="p">)</span>
  1337. <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>
  1338. <span class="c1"># Expected output:</span>
  1339. <span class="c1">#</span>
  1340. <span class="c1"># cancel_me(): before sleep</span>
  1341. <span class="c1"># cancel_me(): cancel sleep</span>
  1342. <span class="c1"># cancel_me(): after sleep</span>
  1343. <span class="c1"># main(): cancel_me is cancelled now</span>
  1344. </pre></div>
  1345. </div>
  1346. </dd></dl>
  1347. <dl class="py method">
  1348. <dt class="sig sig-object py" id="asyncio.Task.cancelled">
  1349. <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.Task.cancelled" title="Link to this definition">¶</a></dt>
  1350. <dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the Task is <em>cancelled</em>.</p>
  1351. <p>The Task is <em>cancelled</em> when the cancellation was requested with
  1352. <a class="reference internal" href="#asyncio.Task.cancel" title="asyncio.Task.cancel"><code class="xref py py-meth docutils literal notranslate"><span class="pre">cancel()</span></code></a> and the wrapped coroutine propagated the
  1353. <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 thrown into it.</p>
  1354. </dd></dl>
  1355. <dl class="py method">
  1356. <dt class="sig sig-object py" id="asyncio.Task.uncancel">
  1357. <span class="sig-name descname"><span class="pre">uncancel</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Task.uncancel" title="Link to this definition">¶</a></dt>
  1358. <dd><p>Decrement the count of cancellation requests to this Task.</p>
  1359. <p>Returns the remaining number of cancellation requests.</p>
  1360. <p>Note that once execution of a cancelled task completed, further
  1361. calls to <a class="reference internal" href="#asyncio.Task.uncancel" title="asyncio.Task.uncancel"><code class="xref py py-meth docutils literal notranslate"><span class="pre">uncancel()</span></code></a> are ineffective.</p>
  1362. <div class="versionadded">
  1363. <p><span class="versionmodified added">New in version 3.11.</span></p>
  1364. </div>
  1365. <p>This method is used by asyncio’s internals and isn’t expected to be
  1366. used by end-user code. In particular, if a Task gets successfully
  1367. uncancelled, this allows for elements of structured concurrency like
  1368. <a class="reference internal" href="#taskgroups"><span class="std std-ref">Task Groups</span></a> and <a class="reference internal" href="#asyncio.timeout" title="asyncio.timeout"><code class="xref py py-func docutils literal notranslate"><span class="pre">asyncio.timeout()</span></code></a> to continue running,
  1369. isolating cancellation to the respective structured block.
  1370. For example:</p>
  1371. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">async</span> <span class="k">def</span> <span class="nf">make_request_with_timeout</span><span class="p">():</span>
  1372. <span class="k">try</span><span class="p">:</span>
  1373. <span class="k">async</span> <span class="k">with</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">timeout</span><span class="p">(</span><span class="mi">1</span><span class="p">):</span>
  1374. <span class="c1"># Structured block affected by the timeout:</span>
  1375. <span class="k">await</span> <span class="n">make_request</span><span class="p">()</span>
  1376. <span class="k">await</span> <span class="n">make_another_request</span><span class="p">()</span>
  1377. <span class="k">except</span> <span class="ne">TimeoutError</span><span class="p">:</span>
  1378. <span class="n">log</span><span class="p">(</span><span class="s2">&quot;There was a timeout&quot;</span><span class="p">)</span>
  1379. <span class="c1"># Outer code not affected by the timeout:</span>
  1380. <span class="k">await</span> <span class="n">unrelated_code</span><span class="p">()</span>
  1381. </pre></div>
  1382. </div>
  1383. <p>While the block with <code class="docutils literal notranslate"><span class="pre">make_request()</span></code> and <code class="docutils literal notranslate"><span class="pre">make_another_request()</span></code>
  1384. might get cancelled due to the timeout, <code class="docutils literal notranslate"><span class="pre">unrelated_code()</span></code> should
  1385. continue running even in case of the timeout. This is implemented
  1386. with <a class="reference internal" href="#asyncio.Task.uncancel" title="asyncio.Task.uncancel"><code class="xref py py-meth docutils literal notranslate"><span class="pre">uncancel()</span></code></a>. <a class="reference internal" href="#asyncio.TaskGroup" title="asyncio.TaskGroup"><code class="xref py py-class docutils literal notranslate"><span class="pre">TaskGroup</span></code></a> context managers use
  1387. <a class="reference internal" href="#asyncio.Task.uncancel" title="asyncio.Task.uncancel"><code class="xref py py-func docutils literal notranslate"><span class="pre">uncancel()</span></code></a> in a similar fashion.</p>
  1388. <p>If end-user code is, for some reason, suppresing cancellation by
  1389. catching <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>, it needs to call this method to remove
  1390. the cancellation state.</p>
  1391. </dd></dl>
  1392. <dl class="py method">
  1393. <dt class="sig sig-object py" id="asyncio.Task.cancelling">
  1394. <span class="sig-name descname"><span class="pre">cancelling</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Task.cancelling" title="Link to this definition">¶</a></dt>
  1395. <dd><p>Return the number of pending cancellation requests to this Task, i.e.,
  1396. the number of calls to <a class="reference internal" href="#asyncio.Task.cancel" title="asyncio.Task.cancel"><code class="xref py py-meth docutils literal notranslate"><span class="pre">cancel()</span></code></a> less the number of
  1397. <a class="reference internal" href="#asyncio.Task.uncancel" title="asyncio.Task.uncancel"><code class="xref py py-meth docutils literal notranslate"><span class="pre">uncancel()</span></code></a> calls.</p>
  1398. <p>Note that if this number is greater than zero but the Task is
  1399. still executing, <a class="reference internal" href="#asyncio.Task.cancelled" title="asyncio.Task.cancelled"><code class="xref py py-meth docutils literal notranslate"><span class="pre">cancelled()</span></code></a> will still return <code class="docutils literal notranslate"><span class="pre">False</span></code>.
  1400. This is because this number can be lowered by calling <a class="reference internal" href="#asyncio.Task.uncancel" title="asyncio.Task.uncancel"><code class="xref py py-meth docutils literal notranslate"><span class="pre">uncancel()</span></code></a>,
  1401. which can lead to the task not being cancelled after all if the
  1402. cancellation requests go down to zero.</p>
  1403. <p>This method is used by asyncio’s internals and isn’t expected to be
  1404. used by end-user code. See <a class="reference internal" href="#asyncio.Task.uncancel" title="asyncio.Task.uncancel"><code class="xref py py-meth docutils literal notranslate"><span class="pre">uncancel()</span></code></a> for more details.</p>
  1405. <div class="versionadded">
  1406. <p><span class="versionmodified added">New in version 3.11.</span></p>
  1407. </div>
  1408. </dd></dl>
  1409. </dd></dl>
  1410. </section>
  1411. </section>
  1412. <div class="clearer"></div>
  1413. </div>
  1414. </div>
  1415. </div>
  1416. <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
  1417. <div class="sphinxsidebarwrapper">
  1418. <div>
  1419. <h3><a href="../contents.html">Table of Contents</a></h3>
  1420. <ul>
  1421. <li><a class="reference internal" href="#">Coroutines and Tasks</a><ul>
  1422. <li><a class="reference internal" href="#coroutines">Coroutines</a></li>
  1423. <li><a class="reference internal" href="#awaitables">Awaitables</a></li>
  1424. <li><a class="reference internal" href="#creating-tasks">Creating Tasks</a></li>
  1425. <li><a class="reference internal" href="#task-cancellation">Task Cancellation</a></li>
  1426. <li><a class="reference internal" href="#task-groups">Task Groups</a></li>
  1427. <li><a class="reference internal" href="#sleeping">Sleeping</a></li>
  1428. <li><a class="reference internal" href="#running-tasks-concurrently">Running Tasks Concurrently</a></li>
  1429. <li><a class="reference internal" href="#eager-task-factory">Eager Task Factory</a></li>
  1430. <li><a class="reference internal" href="#shielding-from-cancellation">Shielding From Cancellation</a></li>
  1431. <li><a class="reference internal" href="#timeouts">Timeouts</a></li>
  1432. <li><a class="reference internal" href="#waiting-primitives">Waiting Primitives</a></li>
  1433. <li><a class="reference internal" href="#running-in-threads">Running in Threads</a></li>
  1434. <li><a class="reference internal" href="#scheduling-from-other-threads">Scheduling From Other Threads</a></li>
  1435. <li><a class="reference internal" href="#introspection">Introspection</a></li>
  1436. <li><a class="reference internal" href="#task-object">Task Object</a></li>
  1437. </ul>
  1438. </li>
  1439. </ul>
  1440. </div>
  1441. <div>
  1442. <h4>Previous topic</h4>
  1443. <p class="topless"><a href="asyncio-runner.html"
  1444. title="previous chapter">Runners</a></p>
  1445. </div>
  1446. <div>
  1447. <h4>Next topic</h4>
  1448. <p class="topless"><a href="asyncio-stream.html"
  1449. title="next chapter">Streams</a></p>
  1450. </div>
  1451. <div role="note" aria-label="source link">
  1452. <h3>This Page</h3>
  1453. <ul class="this-page-menu">
  1454. <li><a href="../bugs.html">Report a Bug</a></li>
  1455. <li>
  1456. <a href="https://github.com/python/cpython/blob/main/Doc/library/asyncio-task.rst"
  1457. rel="nofollow">Show Source
  1458. </a>
  1459. </li>
  1460. </ul>
  1461. </div>
  1462. </div>
  1463. <div id="sidebarbutton" title="Collapse sidebar">
  1464. <span>«</span>
  1465. </div>
  1466. </div>
  1467. <div class="clearer"></div>
  1468. </div>
  1469. <div class="related" role="navigation" aria-label="related navigation">
  1470. <h3>Navigation</h3>
  1471. <ul>
  1472. <li class="right" style="margin-right: 10px">
  1473. <a href="../genindex.html" title="General Index"
  1474. >index</a></li>
  1475. <li class="right" >
  1476. <a href="../py-modindex.html" title="Python Module Index"
  1477. >modules</a> |</li>
  1478. <li class="right" >
  1479. <a href="asyncio-stream.html" title="Streams"
  1480. >next</a> |</li>
  1481. <li class="right" >
  1482. <a href="asyncio-runner.html" title="Runners"
  1483. >previous</a> |</li>
  1484. <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  1485. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  1486. <li class="switchers">
  1487. <div class="language_switcher_placeholder"></div>
  1488. <div class="version_switcher_placeholder"></div>
  1489. </li>
  1490. <li>
  1491. </li>
  1492. <li id="cpython-language-and-version">
  1493. <a href="../index.html">3.12.3 Documentation</a> &#187;
  1494. </li>
  1495. <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
  1496. <li class="nav-item nav-item-2"><a href="ipc.html" >Networking and Interprocess Communication</a> &#187;</li>
  1497. <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>
  1498. <li class="nav-item nav-item-this"><a href="">Coroutines and Tasks</a></li>
  1499. <li class="right">
  1500. <div class="inline-search" role="search">
  1501. <form class="inline-search" action="../search.html" method="get">
  1502. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
  1503. <input type="submit" value="Go" />
  1504. </form>
  1505. </div>
  1506. |
  1507. </li>
  1508. <li class="right">
  1509. <label class="theme-selector-label">
  1510. Theme
  1511. <select class="theme-selector" oninput="activateTheme(this.value)">
  1512. <option value="auto" selected>Auto</option>
  1513. <option value="light">Light</option>
  1514. <option value="dark">Dark</option>
  1515. </select>
  1516. </label> |</li>
  1517. </ul>
  1518. </div>
  1519. <div class="footer">
  1520. &copy;
  1521. <a href="../copyright.html">
  1522. Copyright
  1523. </a>
  1524. 2001-2024, Python Software Foundation.
  1525. <br />
  1526. This page is licensed under the Python Software Foundation License Version 2.
  1527. <br />
  1528. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
  1529. <br />
  1530. See <a href="/license.html">History and License</a> for more information.<br />
  1531. <br />
  1532. The Python Software Foundation is a non-profit corporation.
  1533. <a href="https://www.python.org/psf/donations/">Please donate.</a>
  1534. <br />
  1535. <br />
  1536. Last updated on Apr 09, 2024 (13:47 UTC).
  1537. <a href="/bugs.html">Found a bug</a>?
  1538. <br />
  1539. Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 7.2.6.
  1540. </div>
  1541. </body>
  1542. </html>
上海开阖软件有限公司 沪ICP备12045867号-1