Spaces:
Sleeping
Sleeping
0-Parth-D commited on
Commit ·
dcac338
0
Parent(s):
Initial Commit
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .dockerignoreAdded+10
- DockerfileAdded+18
- docs/__future__.htmlAdded+560
- docs/__main__.htmlAdded+702
- docs/_thread.htmlAdded+553
- docs/abc.htmlAdded+695
- docs/aifc.htmlAdded+353
- docs/allos.htmlAdded+513
- docs/annotationlib.htmlAdded
- docs/archiving.htmlAdded+429
- docs/argparse.htmlAdded
- docs/array.htmlAdded+700
- docs/ast.htmlAdded
- docs/asynchat.htmlAdded+354
- docs/asyncio-api-index.htmlAdded+597
- docs/asyncio-dev.htmlAdded+587
- docs/asyncio-eventloop.htmlAdded
- docs/asyncio-exceptions.htmlAdded+420
- docs/asyncio-extending.htmlAdded+454
- docs/asyncio-future.htmlAdded+636
- docs/asyncio-graph.htmlAdded+494
- docs/asyncio-llapi-index.htmlAdded+935
- docs/asyncio-platforms.htmlAdded+450
- docs/asyncio-policy.htmlAdded+528
- docs/asyncio-protocol.htmlAdded
- docs/asyncio-queue.htmlAdded+626
- docs/asyncio-runner.htmlAdded+534
- docs/asyncio-stream.htmlAdded+941
- docs/asyncio-subprocess.htmlAdded+716
- docs/asyncio-sync.htmlAdded+844
- docs/asyncio-task.htmlAdded
- docs/asyncio.htmlAdded+459
- docs/asyncore.htmlAdded+354
- docs/atexit.htmlAdded
- docs/audioop.htmlAdded
- docs/audit_events.htmlAdded
- docs/base64.htmlAdded
- docs/bdb.htmlAdded
- docs/binary.htmlAdded
- docs/binascii.htmlAdded
- docs/bisect.htmlAdded
- docs/builtins.htmlAdded
- docs/bz2.htmlAdded
- docs/calendar.htmlAdded
- docs/cgi.htmlAdded
- docs/cgitb.htmlAdded
- docs/chunk.htmlAdded
- docs/cmath.htmlAdded
- docs/cmd.htmlAdded
- docs/cmdline.htmlAdded
12345678910venv/__pycache__/*.pyc*.pyo.git/.vscode/*.ipynbchroma_db/.env*.egg-info/123456789101112131415161718FROM python:3.10-slim
WORKDIR /app
RUN python -m venv /opt/venvENV PATH="/opt/venv/bin:$PATH"
COPY requirements.txt .
RUN pip install --no-cache-dir --upgrade pip \ && pip install --no-cache-dir torch --index-url https://download.pytorch.org/whl/cpu \ && pip install --no-cache-dir -r requirements.txt
RUN python -c "from sentence_transformers import SentenceTransformer; SentenceTransformer('all-MiniLM-L6-v2')"
COPY src/rag_code_assistant/agent.py .
CMD ["python", "agent.py"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560<!DOCTYPE html>
<html lang="en" data-content_root="../"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta property="og:title" content="__future__ — Future statement definitions" /><meta property="og:type" content="website" /><meta property="og:url" content="https://docs.python.org/3/library/__future__.html" /><meta property="og:site_name" content="Python documentation" /><meta property="og:description" content="Source code: Lib/__future__.py Imports of the form from __future__ import feature are called future statements. These are special-cased by the Python compiler to allow the use of new Python feature..." /><meta property="og:image:width" content="1146" /><meta property="og:image:height" content="600" /><meta property="og:image" content="https://docs.python.org/3.15/_images/social_previews/summary_library___future___bd12f099.png" /><meta property="og:image:alt" content="Source code: Lib/__future__.py Imports of the form from __future__ import feature are called future statements. These are special-cased by the Python compiler to allow the use of new Python feature..." /><meta name="description" content="Source code: Lib/__future__.py Imports of the form from __future__ import feature are called future statements. These are special-cased by the Python compiler to allow the use of new Python feature..." /><meta name="twitter:card" content="summary_large_image" /><meta name="theme-color" content="#3776ab">
<title>__future__ — Future statement definitions — Python 3.15.0a6 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" /> <link rel="stylesheet" type="text/css" href="../_static/classic.css?v=234b1a7c" /> <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=89a2f22a" /> <link rel="stylesheet" type="text/css" href="../_static/profiling-sampling-visualization.css?v=0c2600ae" /> <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" /> <script src="../_static/documentation_options.js?v=6b7c9ff5"></script> <script src="../_static/doctools.js?v=9bcbadda"></script> <script src="../_static/sphinx_highlight.js?v=dc90522c"></script> <script src="../_static/profiling-sampling-visualization.js?v=9811ed04"></script> <script src="../_static/sidebar.js"></script> <link rel="search" type="application/opensearchdescription+xml" title="Search within Python 3.15.0a6 documentation" href="../_static/opensearch.xml"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="copyright" title="Copyright" href="../copyright.html" /> <link rel="next" title="gc — Garbage Collector interface" href="gc.html" /> <link rel="prev" title="traceback — Print or retrieve a stack traceback" href="traceback.html" /> <script defer file-types="bz2,epub,zip" data-domain="docs.python.org" src="https://analytics.python.org/js/script.file-downloads.outbound-links.js"></script> <link rel="canonical" href="https://docs.python.org/3/library/__future__.html">
<style> @media only screen { table.full-width-table { width: 100%; } } </style><link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css"> <link rel="shortcut icon" type="image/png" href="../_static/py.svg"> <script type="text/javascript" src="../_static/copybutton.js"></script> <script type="text/javascript" src="../_static/menu.js"></script> <script type="text/javascript" src="../_static/search-focus.js"></script> <script type="text/javascript" src="../_static/themetoggle.js"></script> <script type="text/javascript" src="../_static/rtd_switcher.js"></script> <meta name="readthedocs-addons-api-version" content="1">
</head><body><div class="mobile-nav"> <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation" aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu"> <nav class="nav-content" role="navigation"> <label for="menuToggler" class="toggler__label"> <span></span> </label> <span class="nav-items-wrapper"> <a href="https://www.python.org/" class="nav-logo"> <img src="../_static/py.svg" alt="Python logo"> </a> <span class="version_switcher_placeholder"></span> <form role="search" class="search" action="../search.html" method="get"> <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon"> <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> </svg> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q"> <input type="submit" value="Go"> </form> </span> </nav> <div class="menu-wrapper"> <nav class="menu" role="navigation" aria-label="main navigation"> <div class="language_switcher_placeholder"></div> <label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> <div> <h3><a href="../contents.html">Table of Contents</a></h3> <ul><li><a class="reference internal" href="#"><code class="xref py py-mod docutils literal notranslate"><span class="pre">__future__</span></code> — Future statement definitions</a><ul><li><a class="reference internal" href="#module-contents">Module Contents</a></li></ul></li></ul>
</div> <div> <h4>Previous topic</h4> <p class="topless"><a href="traceback.html" title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">traceback</span></code> — Print or retrieve a stack traceback</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="gc.html" title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">gc</span></code> — Garbage Collector interface</a></p> </div> <script> document.addEventListener('DOMContentLoaded', () => { const title = document.querySelector('meta[property="og:title"]').content; const elements = document.querySelectorAll('.improvepage'); const pageurl = window.location.href.split('?')[0]; elements.forEach(element => { const url = new URL(element.href.split('?')[0].replace("-nojs", "")); url.searchParams.set('pagetitle', title); url.searchParams.set('pageurl', pageurl); url.searchParams.set('pagesource', "library/__future__.rst"); element.href = url.toString(); }); }); </script> <div role="note" aria-label="source link"> <h3>This page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a bug</a></li> <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li> <li> <a href="https://github.com/python/cpython/blob/main/Doc/library/__future__.rst?plain=1" rel="nofollow">Show source </a> </li> </ul> </div> </nav> </div></div>
<div class="related" role="navigation" aria-label="Related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="gc.html" title="gc — Garbage Collector interface" accesskey="N">next</a> |</li> <li class="right" > <a href="traceback.html" title="traceback — Print or retrieve a stack traceback" accesskey="P">previous</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.15.0a6 Documentation</a> » </li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="python.html" accesskey="U">Python Runtime Services</a> »</li> <li class="nav-item nav-item-this"><a href=""><code class="xref py py-mod docutils literal notranslate"><span class="pre">__future__</span></code> — Future statement definitions</a></li> <li class="right">
<div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box"> <input type="submit" value="Go"> </form> </div> | </li> <li class="right"><label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> |</li> </ul> </div>
<div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <section id="module-__future__"><span id="future-future-statement-definitions"></span><h1><code class="xref py py-mod docutils literal notranslate"><span class="pre">__future__</span></code> — Future statement definitions<a class="headerlink" href="#module-__future__" title="Link to this heading">¶</a></h1><p><strong>Source code:</strong> <a class="extlink-source reference external" href="https://github.com/python/cpython/tree/main/Lib/__future__.py">Lib/__future__.py</a></p><hr class="docutils" /><p>Imports of the form <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">__future__</span> <span class="pre">import</span> <span class="pre">feature</span></code> are called<a class="reference internal" href="../reference/simple_stmts.html#future"><span class="std std-ref">future statements</span></a>. These are special-cased by the Python compilerto allow the use of new Python features in modules containing the future statementbefore the release in which the feature becomes standard.</p><p>While these future statements are given additional special meaning by thePython compiler, they are still executed like any other import statement andthe <code class="xref py py-mod docutils literal notranslate"><span class="pre">__future__</span></code> exists and is handled by the import system the same wayany other Python module would be. This design serves three purposes:</p><ul class="simple"><li><p>To avoid confusing existing tools that analyze import statements and expect tofind the modules they’re importing.</p></li><li><p>To document when incompatible changes were introduced, and when they will be— or were — made mandatory. This is a form of executable documentation, andcan be inspected programmatically via importing <code class="xref py py-mod docutils literal notranslate"><span class="pre">__future__</span></code> and examiningits contents.</p></li><li><p>To ensure that <a class="reference internal" href="../reference/simple_stmts.html#future"><span class="std std-ref">future statements</span></a> run under releases prior toPython 2.1 at least yield runtime exceptions (the import of <code class="xref py py-mod docutils literal notranslate"><span class="pre">__future__</span></code>will fail, because there was no module of that name prior to 2.1).</p></li></ul><section id="module-contents"><h2>Module Contents<a class="headerlink" href="#module-contents" title="Link to this heading">¶</a></h2><p>No feature description will ever be deleted from <code class="xref py py-mod docutils literal notranslate"><span class="pre">__future__</span></code>. Since itsintroduction in Python 2.1 the following features have found their way into thelanguage using this mechanism:</p><table class="docutils align-default"><thead><tr class="row-odd"><th class="head"><p>feature</p></th><th class="head"><p>optional in</p></th><th class="head"><p>mandatory in</p></th><th class="head"><p>effect</p></th></tr></thead><tbody><tr class="row-even"><td><dl class="py data"><dt class="sig sig-object py" id="future__.nested_scopes"><span class="sig-prename descclassname"><span class="pre">__future__.</span></span><span class="sig-name descname"><span class="pre">nested_scopes</span></span><a class="headerlink" href="#future__.nested_scopes" title="Link to this definition">¶</a></dt><dd></dd></dl>
</td><td><p>2.1.0b1</p></td><td><p>2.2</p></td><td><p><span class="target" id="index-0"></span><a class="pep reference external" href="https://peps.python.org/pep-0227/"><strong>PEP 227</strong></a>: <em>Statically Nested Scopes</em></p></td></tr><tr class="row-odd"><td><dl class="py data"><dt class="sig sig-object py" id="future__.generators"><span class="sig-prename descclassname"><span class="pre">__future__.</span></span><span class="sig-name descname"><span class="pre">generators</span></span><a class="headerlink" href="#future__.generators" title="Link to this definition">¶</a></dt><dd></dd></dl>
</td><td><p>2.2.0a1</p></td><td><p>2.3</p></td><td><p><span class="target" id="index-1"></span><a class="pep reference external" href="https://peps.python.org/pep-0255/"><strong>PEP 255</strong></a>: <em>Simple Generators</em></p></td></tr><tr class="row-even"><td><dl class="py data"><dt class="sig sig-object py" id="future__.division"><span class="sig-prename descclassname"><span class="pre">__future__.</span></span><span class="sig-name descname"><span class="pre">division</span></span><a class="headerlink" href="#future__.division" title="Link to this definition">¶</a></dt><dd></dd></dl>
</td><td><p>2.2.0a2</p></td><td><p>3.0</p></td><td><p><span class="target" id="index-2"></span><a class="pep reference external" href="https://peps.python.org/pep-0238/"><strong>PEP 238</strong></a>: <em>Changing the Division Operator</em></p></td></tr><tr class="row-odd"><td><dl class="py data"><dt class="sig sig-object py" id="future__.absolute_import"><span class="sig-prename descclassname"><span class="pre">__future__.</span></span><span class="sig-name descname"><span class="pre">absolute_import</span></span><a class="headerlink" href="#future__.absolute_import" title="Link to this definition">¶</a></dt><dd></dd></dl>
</td><td><p>2.5.0a1</p></td><td><p>3.0</p></td><td><p><span class="target" id="index-3"></span><a class="pep reference external" href="https://peps.python.org/pep-0328/"><strong>PEP 328</strong></a>: <em>Imports: Multi-Line and Absolute/Relative</em></p></td></tr><tr class="row-even"><td><dl class="py data"><dt class="sig sig-object py" id="future__.with_statement"><span class="sig-prename descclassname"><span class="pre">__future__.</span></span><span class="sig-name descname"><span class="pre">with_statement</span></span><a class="headerlink" href="#future__.with_statement" title="Link to this definition">¶</a></dt><dd></dd></dl>
</td><td><p>2.5.0a1</p></td><td><p>2.6</p></td><td><p><span class="target" id="index-4"></span><a class="pep reference external" href="https://peps.python.org/pep-0343/"><strong>PEP 343</strong></a>: <em>The “with” Statement</em></p></td></tr><tr class="row-odd"><td><dl class="py data"><dt class="sig sig-object py" id="future__.print_function"><span class="sig-prename descclassname"><span class="pre">__future__.</span></span><span class="sig-name descname"><span class="pre">print_function</span></span><a class="headerlink" href="#future__.print_function" title="Link to this definition">¶</a></dt><dd></dd></dl>
</td><td><p>2.6.0a2</p></td><td><p>3.0</p></td><td><p><span class="target" id="index-5"></span><a class="pep reference external" href="https://peps.python.org/pep-3105/"><strong>PEP 3105</strong></a>: <em>Make print a function</em></p></td></tr><tr class="row-even"><td><dl class="py data"><dt class="sig sig-object py" id="future__.unicode_literals"><span class="sig-prename descclassname"><span class="pre">__future__.</span></span><span class="sig-name descname"><span class="pre">unicode_literals</span></span><a class="headerlink" href="#future__.unicode_literals" title="Link to this definition">¶</a></dt><dd></dd></dl>
</td><td><p>2.6.0a2</p></td><td><p>3.0</p></td><td><p><span class="target" id="index-6"></span><a class="pep reference external" href="https://peps.python.org/pep-3112/"><strong>PEP 3112</strong></a>: <em>Bytes literals in Python 3000</em></p></td></tr><tr class="row-odd"><td><dl class="py data"><dt class="sig sig-object py" id="future__.generator_stop"><span class="sig-prename descclassname"><span class="pre">__future__.</span></span><span class="sig-name descname"><span class="pre">generator_stop</span></span><a class="headerlink" href="#future__.generator_stop" title="Link to this definition">¶</a></dt><dd></dd></dl>
</td><td><p>3.5.0b1</p></td><td><p>3.7</p></td><td><p><span class="target" id="index-7"></span><a class="pep reference external" href="https://peps.python.org/pep-0479/"><strong>PEP 479</strong></a>: <em>StopIteration handling inside generators</em></p></td></tr><tr class="row-even"><td><dl class="py data"><dt class="sig sig-object py" id="future__.annotations"><span class="sig-prename descclassname"><span class="pre">__future__.</span></span><span class="sig-name descname"><span class="pre">annotations</span></span><a class="headerlink" href="#future__.annotations" title="Link to this definition">¶</a></dt><dd></dd></dl>
</td><td><p>3.7.0b1</p></td><td><p>Never <a class="footnote-reference brackets" href="#id2" id="id1" role="doc-noteref"><span class="fn-bracket">[</span>1<span class="fn-bracket">]</span></a></p></td><td><p><span class="target" id="index-8"></span><a class="pep reference external" href="https://peps.python.org/pep-0563/"><strong>PEP 563</strong></a>: <em>Postponed evaluation of annotations</em>,<span class="target" id="index-9"></span><a class="pep reference external" href="https://peps.python.org/pep-0649/"><strong>PEP 649</strong></a>: <em>Deferred evaluation of annotations using descriptors</em></p></td></tr></tbody></table><dl class="py class" id="future-classes"><dt class="sig sig-object py" id="future__._Feature"><em class="property"><span class="k"><span class="pre">class</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">__future__.</span></span><span class="sig-name descname"><span class="pre">_Feature</span></span><a class="headerlink" href="#future__._Feature" title="Link to this definition">¶</a></dt><dd><p>Each statement in <code class="file docutils literal notranslate"><span class="pre">__future__.py</span></code> is of the form:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">FeatureName</span> <span class="o">=</span> <span class="n">_Feature</span><span class="p">(</span><span class="n">OptionalRelease</span><span class="p">,</span> <span class="n">MandatoryRelease</span><span class="p">,</span> <span class="n">CompilerFlag</span><span class="p">)</span></pre></div></div><p>where, normally, <em>OptionalRelease</em> is less than <em>MandatoryRelease</em>, and both are5-tuples of the same form as <a class="reference internal" href="sys.html#sys.version_info" title="sys.version_info"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.version_info</span></code></a>:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="p">(</span><span class="n">PY_MAJOR_VERSION</span><span class="p">,</span> <span class="c1"># the 2 in 2.1.0a3; an int</span> <span class="n">PY_MINOR_VERSION</span><span class="p">,</span> <span class="c1"># the 1; an int</span> <span class="n">PY_MICRO_VERSION</span><span class="p">,</span> <span class="c1"># the 0; an int</span> <span class="n">PY_RELEASE_LEVEL</span><span class="p">,</span> <span class="c1"># "alpha", "beta", "candidate" or "final"; string</span> <span class="n">PY_RELEASE_SERIAL</span> <span class="c1"># the 3; an int</span><span class="p">)</span></pre></div></div></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="future__._Feature.getOptionalRelease"><span class="sig-prename descclassname"><span class="pre">_Feature.</span></span><span class="sig-name descname"><span class="pre">getOptionalRelease</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#future__._Feature.getOptionalRelease" title="Link to this definition">¶</a></dt><dd><p><em>OptionalRelease</em> records the first release in which the feature was accepted.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="future__._Feature.getMandatoryRelease"><span class="sig-prename descclassname"><span class="pre">_Feature.</span></span><span class="sig-name descname"><span class="pre">getMandatoryRelease</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#future__._Feature.getMandatoryRelease" title="Link to this definition">¶</a></dt><dd><p>In the case of a <em>MandatoryRelease</em> that has not yet occurred,<em>MandatoryRelease</em> predicts the release in which the feature will become part ofthe language.</p><p>Else <em>MandatoryRelease</em> records when the feature became part of the language; inreleases at or after that, modules no longer need a future statement to use thefeature in question, but may continue to use such imports.</p><p><em>MandatoryRelease</em> may also be <code class="docutils literal notranslate"><span class="pre">None</span></code>, meaning that a planned feature gotdropped or that it is not yet decided.</p></dd></dl>
<dl class="py attribute"><dt class="sig sig-object py" id="future__._Feature.compiler_flag"><span class="sig-prename descclassname"><span class="pre">_Feature.</span></span><span class="sig-name descname"><span class="pre">compiler_flag</span></span><a class="headerlink" href="#future__._Feature.compiler_flag" title="Link to this definition">¶</a></dt><dd><p><em>CompilerFlag</em> is the (bitfield) flag that should be passed in the fourthargument to the built-in function <a class="reference internal" href="functions.html#compile" title="compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">compile()</span></code></a> to enable the feature indynamically compiled code. This flag is stored in the <code class="xref py py-attr docutils literal notranslate"><span class="pre">_Feature.compiler_flag</span></code>attribute on <a class="reference internal" href="#future__._Feature" title="__future__._Feature"><code class="xref py py-class docutils literal notranslate"><span class="pre">_Feature</span></code></a> instances.</p></dd></dl>
<aside class="footnote-list brackets"><aside class="footnote brackets" id="id2" role="doc-footnote"><span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id1">1</a><span class="fn-bracket">]</span></span><p><code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">__future__</span> <span class="pre">import</span> <span class="pre">annotations</span></code> was previously scheduled tobecome mandatory in Python 3.10, but the change was delayed and ultimatelycanceled. This feature will eventually be deprecated and removed. See<span class="target" id="index-10"></span><a class="pep reference external" href="https://peps.python.org/pep-0649/"><strong>PEP 649</strong></a> and <span class="target" id="index-11"></span><a class="pep reference external" href="https://peps.python.org/pep-0749/"><strong>PEP 749</strong></a>.</p></aside></aside><div class="admonition seealso"><p class="admonition-title">See also</p><dl class="simple"><dt><a class="reference internal" href="../reference/simple_stmts.html#future"><span class="std std-ref">Future statements</span></a></dt><dd><p>How the compiler treats future imports.</p></dd><dt><span class="target" id="index-12"></span><a class="pep reference external" href="https://peps.python.org/pep-0236/"><strong>PEP 236</strong></a> - Back to the __future__</dt><dd><p>The original proposal for the __future__ mechanism.</p></dd></dl></div></section></section>
<div class="clearer"></div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="Main"> <div class="sphinxsidebarwrapper"> <div> <h3><a href="../contents.html">Table of Contents</a></h3> <ul><li><a class="reference internal" href="#"><code class="xref py py-mod docutils literal notranslate"><span class="pre">__future__</span></code> — Future statement definitions</a><ul><li><a class="reference internal" href="#module-contents">Module Contents</a></li></ul></li></ul>
</div> <div> <h4>Previous topic</h4> <p class="topless"><a href="traceback.html" title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">traceback</span></code> — Print or retrieve a stack traceback</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="gc.html" title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">gc</span></code> — Garbage Collector interface</a></p> </div> <script> document.addEventListener('DOMContentLoaded', () => { const title = document.querySelector('meta[property="og:title"]').content; const elements = document.querySelectorAll('.improvepage'); const pageurl = window.location.href.split('?')[0]; elements.forEach(element => { const url = new URL(element.href.split('?')[0].replace("-nojs", "")); url.searchParams.set('pagetitle', title); url.searchParams.set('pageurl', pageurl); url.searchParams.set('pagesource', "library/__future__.rst"); element.href = url.toString(); }); }); </script> <div role="note" aria-label="source link"> <h3>This page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a bug</a></li> <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li> <li> <a href="https://github.com/python/cpython/blob/main/Doc/library/__future__.rst?plain=1" rel="nofollow">Show source </a> </li> </ul> </div> </div><div id="sidebarbutton" title="Collapse sidebar"><span>«</span></div>
</div> <div class="clearer"></div> </div> <div class="related" role="navigation" aria-label="Related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="gc.html" title="gc — Garbage Collector interface" >next</a> |</li> <li class="right" > <a href="traceback.html" title="traceback — Print or retrieve a stack traceback" >previous</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.15.0a6 Documentation</a> » </li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="python.html" >Python Runtime Services</a> »</li> <li class="nav-item nav-item-this"><a href=""><code class="xref py py-mod docutils literal notranslate"><span class="pre">__future__</span></code> — Future statement definitions</a></li> <li class="right">
<div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box"> <input type="submit" value="Go"> </form> </div> | </li> <li class="right"><label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> |</li> </ul> </div> <div class="footer"> © <a href="../copyright.html">Copyright</a> 2001 Python Software Foundation. <br> This page is licensed under the Python Software Foundation License Version 2. <br> Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. <br> See <a href="/license.html">History and License</a> for more information.<br> <br>
The Python Software Foundation is a non-profit corporation.<a href="https://www.python.org/psf/donations/">Please donate.</a><br> <br> Last updated on Mar 10, 2026 (08:58 UTC). <a href="/bugs.html">Found a bug</a>? <br>
Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3. </div>
</body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702<!DOCTYPE html>
<html lang="en" data-content_root="../"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta property="og:title" content="__main__ — Top-level code environment" /><meta property="og:type" content="website" /><meta property="og:url" content="https://docs.python.org/3/library/__main__.html" /><meta property="og:site_name" content="Python documentation" /><meta property="og:description" content="In Python, the special name__main__ is used for two important constructs: the name of the top-level environment of the program, which can be checked using the__name__ == '__main__' expres..." /><meta property="og:image:width" content="1146" /><meta property="og:image:height" content="600" /><meta property="og:image" content="https://docs.python.org/3.15/_images/social_previews/summary_library___main___4cbae4b7.png" /><meta property="og:image:alt" content="In Python, the special name__main__ is used for two important constructs: the name of the top-level environment of the program, which can be checked using the__name__ == '__main__' expres..." /><meta name="description" content="In Python, the special name__main__ is used for two important constructs: the name of the top-level environment of the program, which can be checked using the__name__ == '__main__' expres..." /><meta name="twitter:card" content="summary_large_image" /><meta name="theme-color" content="#3776ab">
<title>__main__ — Top-level code environment — Python 3.15.0a6 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" /> <link rel="stylesheet" type="text/css" href="../_static/classic.css?v=234b1a7c" /> <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=89a2f22a" /> <link rel="stylesheet" type="text/css" href="../_static/profiling-sampling-visualization.css?v=0c2600ae" /> <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" /> <script src="../_static/documentation_options.js?v=6b7c9ff5"></script> <script src="../_static/doctools.js?v=9bcbadda"></script> <script src="../_static/sphinx_highlight.js?v=dc90522c"></script> <script src="../_static/profiling-sampling-visualization.js?v=9811ed04"></script> <script src="../_static/sidebar.js"></script> <link rel="search" type="application/opensearchdescription+xml" title="Search within Python 3.15.0a6 documentation" href="../_static/opensearch.xml"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="copyright" title="Copyright" href="../copyright.html" /> <link rel="next" title="warnings — Warning control" href="warnings.html" /> <link rel="prev" title="builtins — Built-in objects" href="builtins.html" /> <script defer file-types="bz2,epub,zip" data-domain="docs.python.org" src="https://analytics.python.org/js/script.file-downloads.outbound-links.js"></script> <link rel="canonical" href="https://docs.python.org/3/library/__main__.html">
<style> @media only screen { table.full-width-table { width: 100%; } } </style><link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css"> <link rel="shortcut icon" type="image/png" href="../_static/py.svg"> <script type="text/javascript" src="../_static/copybutton.js"></script> <script type="text/javascript" src="../_static/menu.js"></script> <script type="text/javascript" src="../_static/search-focus.js"></script> <script type="text/javascript" src="../_static/themetoggle.js"></script> <script type="text/javascript" src="../_static/rtd_switcher.js"></script> <meta name="readthedocs-addons-api-version" content="1">
</head><body><div class="mobile-nav"> <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation" aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu"> <nav class="nav-content" role="navigation"> <label for="menuToggler" class="toggler__label"> <span></span> </label> <span class="nav-items-wrapper"> <a href="https://www.python.org/" class="nav-logo"> <img src="../_static/py.svg" alt="Python logo"> </a> <span class="version_switcher_placeholder"></span> <form role="search" class="search" action="../search.html" method="get"> <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon"> <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> </svg> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q"> <input type="submit" value="Go"> </form> </span> </nav> <div class="menu-wrapper"> <nav class="menu" role="navigation" aria-label="main navigation"> <div class="language_switcher_placeholder"></div> <label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> <div> <h3><a href="../contents.html">Table of Contents</a></h3> <ul><li><a class="reference internal" href="#"><code class="xref py py-mod docutils literal notranslate"><span class="pre">__main__</span></code> — Top-level code environment</a><ul><li><a class="reference internal" href="#name-main"><code class="docutils literal notranslate"><span class="pre">__name__</span> <span class="pre">==</span> <span class="pre">'__main__'</span></code></a><ul><li><a class="reference internal" href="#what-is-the-top-level-code-environment">What is the “top-level code environment”?</a></li><li><a class="reference internal" href="#idiomatic-usage">Idiomatic Usage</a></li><li><a class="reference internal" href="#packaging-considerations">Packaging Considerations</a></li></ul></li><li><a class="reference internal" href="#main-py-in-python-packages"><code class="docutils literal notranslate"><span class="pre">__main__.py</span></code> in Python Packages</a><ul><li><a class="reference internal" href="#id1">Idiomatic Usage</a></li></ul></li><li><a class="reference internal" href="#import-main"><code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">__main__</span></code></a></li></ul></li></ul>
</div> <div> <h4>Previous topic</h4> <p class="topless"><a href="builtins.html" title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">builtins</span></code> — Built-in objects</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="warnings.html" title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">warnings</span></code> — Warning control</a></p> </div> <script> document.addEventListener('DOMContentLoaded', () => { const title = document.querySelector('meta[property="og:title"]').content; const elements = document.querySelectorAll('.improvepage'); const pageurl = window.location.href.split('?')[0]; elements.forEach(element => { const url = new URL(element.href.split('?')[0].replace("-nojs", "")); url.searchParams.set('pagetitle', title); url.searchParams.set('pageurl', pageurl); url.searchParams.set('pagesource', "library/__main__.rst"); element.href = url.toString(); }); }); </script> <div role="note" aria-label="source link"> <h3>This page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a bug</a></li> <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li> <li> <a href="https://github.com/python/cpython/blob/main/Doc/library/__main__.rst?plain=1" rel="nofollow">Show source </a> </li> </ul> </div> </nav> </div></div>
<div class="related" role="navigation" aria-label="Related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="warnings.html" title="warnings — Warning control" accesskey="N">next</a> |</li> <li class="right" > <a href="builtins.html" title="builtins — Built-in objects" accesskey="P">previous</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.15.0a6 Documentation</a> » </li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="python.html" accesskey="U">Python Runtime Services</a> »</li> <li class="nav-item nav-item-this"><a href=""><code class="xref py py-mod docutils literal notranslate"><span class="pre">__main__</span></code> — Top-level code environment</a></li> <li class="right">
<div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box"> <input type="submit" value="Go"> </form> </div> | </li> <li class="right"><label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> |</li> </ul> </div>
<div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <section id="module-__main__"><span id="main-top-level-code-environment"></span><h1><code class="xref py py-mod docutils literal notranslate"><span class="pre">__main__</span></code> — Top-level code environment<a class="headerlink" href="#module-__main__" title="Link to this heading">¶</a></h1><hr class="docutils" /><p>In Python, the special name <code class="docutils literal notranslate"><span class="pre">__main__</span></code> is used for two important constructs:</p><ol class="arabic simple"><li><p>the name of the top-level environment of the program, which can bechecked using the <code class="docutils literal notranslate"><span class="pre">__name__</span> <span class="pre">==</span> <span class="pre">'__main__'</span></code> expression; and</p></li><li><p>the <code class="docutils literal notranslate"><span class="pre">__main__.py</span></code> file in Python packages.</p></li></ol><p>Both of these mechanisms are related to Python modules; how users interact withthem and how they interact with each other. They are explained in detailbelow. If you’re new to Python modules, see the tutorial section<a class="reference internal" href="../tutorial/modules.html#tut-modules"><span class="std std-ref">Modules</span></a> for an introduction.</p><section id="name-main"><span id="name-equals-main"></span><h2><code class="docutils literal notranslate"><span class="pre">__name__</span> <span class="pre">==</span> <span class="pre">'__main__'</span></code><a class="headerlink" href="#name-main" title="Link to this heading">¶</a></h2><p>When a Python module or package is imported, <code class="docutils literal notranslate"><span class="pre">__name__</span></code> is set to themodule’s name. Usually, this is the name of the Python file itself without the<code class="docutils literal notranslate"><span class="pre">.py</span></code> extension:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">import</span><span class="w"> </span><span class="nn">configparser</span><span class="gp">>>> </span><span class="n">configparser</span><span class="o">.</span><span class="vm">__name__</span><span class="go">'configparser'</span></pre></div></div><p>If the file is part of a package, <code class="docutils literal notranslate"><span class="pre">__name__</span></code> will also include the parentpackage’s path:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span><span class="w"> </span><span class="nn">concurrent.futures</span><span class="w"> </span><span class="kn">import</span> <span class="n">process</span><span class="gp">>>> </span><span class="n">process</span><span class="o">.</span><span class="vm">__name__</span><span class="go">'concurrent.futures.process'</span></pre></div></div><p>However, if the module is executed in the top-level code environment,its <code class="docutils literal notranslate"><span class="pre">__name__</span></code> is set to the string <code class="docutils literal notranslate"><span class="pre">'__main__'</span></code>.</p><section id="what-is-the-top-level-code-environment"><h3>What is the “top-level code environment”?<a class="headerlink" href="#what-is-the-top-level-code-environment" title="Link to this heading">¶</a></h3><p><code class="docutils literal notranslate"><span class="pre">__main__</span></code> is the name of the environment where top-level code is run.“Top-level code” is the first user-specified Python module that starts running.It’s “top-level” because it imports all other modules that the program needs.Sometimes “top-level code” is called an <em>entry point</em> to the application.</p><p>The top-level code environment can be:</p><ul><li><p>the scope of an interactive prompt:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="vm">__name__</span><span class="go">'__main__'</span></pre></div></div></li><li><p>the Python module passed to the Python interpreter as a file argument:</p><div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span>python<span class="w"> </span>helloworld.py<span class="go">Hello, world!</span></pre></div></div></li><li><p>the Python module or package passed to the Python interpreter with the<a class="reference internal" href="../using/cmdline.html#cmdoption-m"><code class="xref std std-option docutils literal notranslate"><span class="pre">-m</span></code></a> argument:</p><div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span>python<span class="w"> </span>-m<span class="w"> </span>tarfile<span class="go">usage: tarfile.py [-h] [-v] (...)</span></pre></div></div></li><li><p>Python code read by the Python interpreter from standard input:</p><div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span><span class="nb">echo</span><span class="w"> </span><span class="s2">"import this"</span><span class="w"> </span><span class="p">|</span><span class="w"> </span>python<span class="go">The Zen of Python, by Tim Peters</span>
<span class="go">Beautiful is better than ugly.</span><span class="go">Explicit is better than implicit.</span><span class="go">...</span></pre></div></div></li><li><p>Python code passed to the Python interpreter with the <a class="reference internal" href="../using/cmdline.html#cmdoption-c"><code class="xref std std-option docutils literal notranslate"><span class="pre">-c</span></code></a> argument:</p><div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span>python<span class="w"> </span>-c<span class="w"> </span><span class="s2">"import this"</span><span class="go">The Zen of Python, by Tim Peters</span>
<span class="go">Beautiful is better than ugly.</span><span class="go">Explicit is better than implicit.</span><span class="go">...</span></pre></div></div></li></ul><p>In each of these situations, the top-level module’s <code class="docutils literal notranslate"><span class="pre">__name__</span></code> is set to<code class="docutils literal notranslate"><span class="pre">'__main__'</span></code>.</p><p>As a result, a module can discover whether or not it is running in thetop-level environment by checking its own <code class="docutils literal notranslate"><span class="pre">__name__</span></code>, which allows a commonidiom for conditionally executing code when the module is not initialized froman import statement:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">'__main__'</span><span class="p">:</span> <span class="c1"># Execute when the module is not initialized from an import statement.</span> <span class="o">...</span></pre></div></div><div class="admonition seealso"><p class="admonition-title">See also</p><p>For a more detailed look at how <code class="docutils literal notranslate"><span class="pre">__name__</span></code> is set in all situations, seethe tutorial section <a class="reference internal" href="../tutorial/modules.html#tut-modules"><span class="std std-ref">Modules</span></a>.</p></div></section><section id="idiomatic-usage"><h3>Idiomatic Usage<a class="headerlink" href="#idiomatic-usage" title="Link to this heading">¶</a></h3><p>Some modules contain code that is intended for script use only, like parsingcommand-line arguments or fetching data from standard input. If a modulelike this was imported from a different module, for example to unit testit, the script code would unintentionally execute as well.</p><p>This is where using the <code class="docutils literal notranslate"><span class="pre">if</span> <span class="pre">__name__</span> <span class="pre">==</span> <span class="pre">'__main__'</span></code> code block comes inhandy. Code within this block won’t run unless the module is executed in thetop-level environment.</p><p>Putting as few statements as possible in the block below <code class="docutils literal notranslate"><span class="pre">if</span> <span class="pre">__name__</span> <span class="pre">==</span><span class="pre">'__main__'</span></code> can improve code clarity and correctness. Most often, a functionnamed <code class="docutils literal notranslate"><span class="pre">main</span></code> encapsulates the program’s primary behavior:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># echo.py</span>
<span class="kn">import</span><span class="w"> </span><span class="nn">shlex</span><span class="kn">import</span><span class="w"> </span><span class="nn">sys</span>
<span class="k">def</span><span class="w"> </span><span class="nf">echo</span><span class="p">(</span><span class="n">phrase</span><span class="p">:</span> <span class="nb">str</span><span class="p">)</span> <span class="o">-></span> <span class="kc">None</span><span class="p">:</span><span class="w"> </span><span class="sd">"""A dummy wrapper around print."""</span> <span class="c1"># for demonstration purposes, you can imagine that there is some</span> <span class="c1"># valuable and reusable logic inside this function</span> <span class="nb">print</span><span class="p">(</span><span class="n">phrase</span><span class="p">)</span>
<span class="k">def</span><span class="w"> </span><span class="nf">main</span><span class="p">()</span> <span class="o">-></span> <span class="nb">int</span><span class="p">:</span><span class="w"> </span><span class="sd">"""Echo the input arguments to standard output"""</span> <span class="n">phrase</span> <span class="o">=</span> <span class="n">shlex</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">)</span> <span class="n">echo</span><span class="p">(</span><span class="n">phrase</span><span class="p">)</span> <span class="k">return</span> <span class="mi">0</span>
<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">'__main__'</span><span class="p">:</span> <span class="n">sys</span><span class="o">.</span><span class="n">exit</span><span class="p">(</span><span class="n">main</span><span class="p">())</span> <span class="c1"># next section explains the use of sys.exit</span></pre></div></div><p>Note that if the module didn’t encapsulate code inside the <code class="docutils literal notranslate"><span class="pre">main</span></code> functionbut instead put it directly within the <code class="docutils literal notranslate"><span class="pre">if</span> <span class="pre">__name__</span> <span class="pre">==</span> <span class="pre">'__main__'</span></code> block,the <code class="docutils literal notranslate"><span class="pre">phrase</span></code> variable would be global to the entire module. This iserror-prone as other functions within the module could be unintentionally usingthe global variable instead of a local name. A <code class="docutils literal notranslate"><span class="pre">main</span></code> function solves thisproblem.</p><p>Using a <code class="docutils literal notranslate"><span class="pre">main</span></code> function has the added benefit of the <code class="docutils literal notranslate"><span class="pre">echo</span></code> function itselfbeing isolated and importable elsewhere. When <code class="docutils literal notranslate"><span class="pre">echo.py</span></code> is imported, the<code class="docutils literal notranslate"><span class="pre">echo</span></code> and <code class="docutils literal notranslate"><span class="pre">main</span></code> functions will be defined, but neither of them will becalled, because <code class="docutils literal notranslate"><span class="pre">__name__</span> <span class="pre">!=</span> <span class="pre">'__main__'</span></code>.</p></section><section id="packaging-considerations"><h3>Packaging Considerations<a class="headerlink" href="#packaging-considerations" title="Link to this heading">¶</a></h3><p><code class="docutils literal notranslate"><span class="pre">main</span></code> functions are often used to create command-line tools by specifyingthem as entry points for console scripts. When this is done,<a class="reference external" href="https://pip.pypa.io/">pip</a> inserts the function call into a template script,where the return value of <code class="docutils literal notranslate"><span class="pre">main</span></code> is passed into <a class="reference internal" href="sys.html#sys.exit" title="sys.exit"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exit()</span></code></a>.For example:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">sys</span><span class="o">.</span><span class="n">exit</span><span class="p">(</span><span class="n">main</span><span class="p">())</span></pre></div></div><p>Since the call to <code class="docutils literal notranslate"><span class="pre">main</span></code> is wrapped in <a class="reference internal" href="sys.html#sys.exit" title="sys.exit"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exit()</span></code></a>, the expectation isthat your function will return some value acceptable as an input to<code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exit()</span></code>; typically, an integer or <code class="docutils literal notranslate"><span class="pre">None</span></code> (which is implicitlyreturned if your function does not have a return statement).</p><p>By proactively following this convention ourselves, our module will have thesame behavior when run directly (i.e. <code class="docutils literal notranslate"><span class="pre">python</span> <span class="pre">echo.py</span></code>) as it will have ifwe later package it as a console script entry-point in a pip-installablepackage.</p><p>In particular, be careful about returning strings from your <code class="docutils literal notranslate"><span class="pre">main</span></code> function.<a class="reference internal" href="sys.html#sys.exit" title="sys.exit"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exit()</span></code></a> will interpret a string argument as a failure message, soyour program will have an exit code of <code class="docutils literal notranslate"><span class="pre">1</span></code>, indicating failure, and thestring will be written to <a class="reference internal" href="sys.html#sys.stderr" title="sys.stderr"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.stderr</span></code></a>. The <code class="docutils literal notranslate"><span class="pre">echo.py</span></code> example fromearlier exemplifies using the <code class="docutils literal notranslate"><span class="pre">sys.exit(main())</span></code> convention.</p><div class="admonition seealso"><p class="admonition-title">See also</p><p><a class="reference external" href="https://packaging.python.org/">Python Packaging User Guide</a>contains a collection of tutorials and references on how to distribute andinstall Python packages with modern tools.</p></div></section></section><section id="main-py-in-python-packages"><h2><code class="docutils literal notranslate"><span class="pre">__main__.py</span></code> in Python Packages<a class="headerlink" href="#main-py-in-python-packages" title="Link to this heading">¶</a></h2><p>If you are not familiar with Python packages, see section <a class="reference internal" href="../tutorial/modules.html#tut-packages"><span class="std std-ref">Packages</span></a>of the tutorial. Most commonly, the <code class="docutils literal notranslate"><span class="pre">__main__.py</span></code> file is used to providea command-line interface for a package. Consider the following hypotheticalpackage, “bandclass”:</p><div class="highlight-text notranslate"><div class="highlight"><pre><span></span>bandclass ├── __init__.py ├── __main__.py └── student.py</pre></div></div><p><code class="docutils literal notranslate"><span class="pre">__main__.py</span></code> will be executed when the package itself is invokeddirectly from the command line using the <a class="reference internal" href="../using/cmdline.html#cmdoption-m"><code class="xref std std-option docutils literal notranslate"><span class="pre">-m</span></code></a> flag. For example:</p><div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span>python<span class="w"> </span>-m<span class="w"> </span>bandclass</pre></div></div><p>This command will cause <code class="docutils literal notranslate"><span class="pre">__main__.py</span></code> to run. How you utilize this mechanismwill depend on the nature of the package you are writing, but in thishypothetical case, it might make sense to allow the teacher to search forstudents:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># bandclass/__main__.py</span>
<span class="kn">import</span><span class="w"> </span><span class="nn">sys</span><span class="kn">from</span><span class="w"> </span><span class="nn">.student</span><span class="w"> </span><span class="kn">import</span> <span class="n">search_students</span>
<span class="n">student_name</span> <span class="o">=</span> <span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">)</span> <span class="o">>=</span> <span class="mi">2</span> <span class="k">else</span> <span class="s1">''</span><span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">'Found student: </span><span class="si">{</span><span class="n">search_students</span><span class="p">(</span><span class="n">student_name</span><span class="p">)</span><span class="si">}</span><span class="s1">'</span><span class="p">)</span></pre></div></div><p>Note that <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">.student</span> <span class="pre">import</span> <span class="pre">search_students</span></code> is an example of a relativeimport. This import style can be used when referencing modules within apackage. For more details, see <a class="reference internal" href="../tutorial/modules.html#intra-package-references"><span class="std std-ref">Intra-package References</span></a> in the<a class="reference internal" href="../tutorial/modules.html#tut-modules"><span class="std std-ref">Modules</span></a> section of the tutorial.</p><section id="id1"><h3>Idiomatic Usage<a class="headerlink" href="#id1" title="Link to this heading">¶</a></h3><p>The content of <code class="docutils literal notranslate"><span class="pre">__main__.py</span></code> typically isn’t fenced with an<code class="docutils literal notranslate"><span class="pre">if</span> <span class="pre">__name__</span> <span class="pre">==</span> <span class="pre">'__main__'</span></code> block. Instead, those files are keptshort and import functions to execute from other modules. Those other modules can then beeasily unit-tested and are properly reusable.</p><p>If used, an <code class="docutils literal notranslate"><span class="pre">if</span> <span class="pre">__name__</span> <span class="pre">==</span> <span class="pre">'__main__'</span></code> block will still work as expectedfor a <code class="docutils literal notranslate"><span class="pre">__main__.py</span></code> file within a package, because its <code class="docutils literal notranslate"><span class="pre">__name__</span></code>attribute will include the package’s path if imported:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">import</span><span class="w"> </span><span class="nn">asyncio.__main__</span><span class="gp">>>> </span><span class="n">asyncio</span><span class="o">.</span><span class="n">__main__</span><span class="o">.</span><span class="vm">__name__</span><span class="go">'asyncio.__main__'</span></pre></div></div><p>This won’t work for <code class="docutils literal notranslate"><span class="pre">__main__.py</span></code> files in the root directory of a<code class="docutils literal notranslate"><span class="pre">.zip</span></code> file though. Hence, for consistency, a minimal <code class="docutils literal notranslate"><span class="pre">__main__.py</span></code>without a <code class="docutils literal notranslate"><span class="pre">__name__</span></code> check is preferred.</p><div class="admonition seealso"><p class="admonition-title">See also</p><p>See <a class="reference internal" href="venv.html#module-venv" title="venv: Creation of virtual environments."><code class="xref py py-mod docutils literal notranslate"><span class="pre">venv</span></code></a> for an example of a package with a minimal <code class="docutils literal notranslate"><span class="pre">__main__.py</span></code>in the standard library. It doesn’t contain a <code class="docutils literal notranslate"><span class="pre">if</span> <span class="pre">__name__</span> <span class="pre">==</span> <span class="pre">'__main__'</span></code>block. You can invoke it with <code class="docutils literal notranslate"><span class="pre">python</span> <span class="pre">-m</span> <span class="pre">venv</span> <span class="pre">[directory]</span></code>.</p><p>See <a class="reference internal" href="runpy.html#module-runpy" title="runpy: Locate and run Python modules without importing them first."><code class="xref py py-mod docutils literal notranslate"><span class="pre">runpy</span></code></a> for more details on the <a class="reference internal" href="../using/cmdline.html#cmdoption-m"><code class="xref std std-option docutils literal notranslate"><span class="pre">-m</span></code></a> flag to theinterpreter executable.</p><p>See <a class="reference internal" href="zipapp.html#module-zipapp" title="zipapp: Manage executable Python zip archives"><code class="xref py py-mod docutils literal notranslate"><span class="pre">zipapp</span></code></a> for how to run applications packaged as <em>.zip</em> files. Inthis case Python looks for a <code class="docutils literal notranslate"><span class="pre">__main__.py</span></code> file in the root directory ofthe archive.</p></div></section></section><section id="import-main"><h2><code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">__main__</span></code><a class="headerlink" href="#import-main" title="Link to this heading">¶</a></h2><p>Regardless of which module a Python program was started with, other modulesrunning within that same program can import the top-level environment’s scope(<a class="reference internal" href="../glossary.html#term-namespace"><span class="xref std std-term">namespace</span></a>) by importing the <code class="docutils literal notranslate"><span class="pre">__main__</span></code> module. This doesn’t importa <code class="docutils literal notranslate"><span class="pre">__main__.py</span></code> file but rather whichever module that received the specialname <code class="docutils literal notranslate"><span class="pre">'__main__'</span></code>.</p><p>Here is an example module that consumes the <code class="docutils literal notranslate"><span class="pre">__main__</span></code> namespace:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># namely.py</span>
<span class="kn">import</span><span class="w"> </span><span class="nn">__main__</span>
<span class="k">def</span><span class="w"> </span><span class="nf">did_user_define_their_name</span><span class="p">():</span> <span class="k">return</span> <span class="s1">'my_name'</span> <span class="ow">in</span> <span class="nb">dir</span><span class="p">(</span><span class="n">__main__</span><span class="p">)</span>
<span class="k">def</span><span class="w"> </span><span class="nf">print_user_name</span><span class="p">():</span> <span class="k">if</span> <span class="ow">not</span> <span class="n">did_user_define_their_name</span><span class="p">():</span> <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="s1">'Define the variable `my_name`!'</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="n">__main__</span><span class="o">.</span><span class="n">my_name</span><span class="p">)</span></pre></div></div><p>Example usage of this module could be as follows:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># start.py</span>
<span class="kn">import</span><span class="w"> </span><span class="nn">sys</span>
<span class="kn">from</span><span class="w"> </span><span class="nn">namely</span><span class="w"> </span><span class="kn">import</span> <span class="n">print_user_name</span>
<span class="c1"># my_name = "Dinsdale"</span>
<span class="k">def</span><span class="w"> </span><span class="nf">main</span><span class="p">():</span> <span class="k">try</span><span class="p">:</span> <span class="n">print_user_name</span><span class="p">()</span> <span class="k">except</span> <span class="ne">ValueError</span> <span class="k">as</span> <span class="n">ve</span><span class="p">:</span> <span class="k">return</span> <span class="nb">str</span><span class="p">(</span><span class="n">ve</span><span class="p">)</span>
<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s2">"__main__"</span><span class="p">:</span> <span class="n">sys</span><span class="o">.</span><span class="n">exit</span><span class="p">(</span><span class="n">main</span><span class="p">())</span></pre></div></div><p>Now, if we started our program, the result would look like this:</p><div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span>python<span class="w"> </span>start.py<span class="go">Define the variable `my_name`!</span></pre></div></div><p>The exit code of the program would be 1, indicating an error. Uncommenting theline with <code class="docutils literal notranslate"><span class="pre">my_name</span> <span class="pre">=</span> <span class="pre">"Dinsdale"</span></code> fixes the program and now it exits withstatus code 0, indicating success:</p><div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span>python<span class="w"> </span>start.py<span class="go">Dinsdale</span></pre></div></div><p>Note that importing <code class="docutils literal notranslate"><span class="pre">__main__</span></code> doesn’t cause any issues with unintentionallyrunning top-level code meant for script use which is put in the<code class="docutils literal notranslate"><span class="pre">if</span> <span class="pre">__name__</span> <span class="pre">==</span> <span class="pre">"__main__"</span></code> block of the <code class="docutils literal notranslate"><span class="pre">start</span></code> module. Why does this work?</p><p>Python inserts an empty <code class="docutils literal notranslate"><span class="pre">__main__</span></code> module in <a class="reference internal" href="sys.html#sys.modules" title="sys.modules"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.modules</span></code></a> atinterpreter startup, and populates it by running top-level code. In our examplethis is the <code class="docutils literal notranslate"><span class="pre">start</span></code> module which runs line by line and imports <code class="docutils literal notranslate"><span class="pre">namely</span></code>.In turn, <code class="docutils literal notranslate"><span class="pre">namely</span></code> imports <code class="docutils literal notranslate"><span class="pre">__main__</span></code> (which is really <code class="docutils literal notranslate"><span class="pre">start</span></code>). That’s animport cycle! Fortunately, since the partially populated <code class="docutils literal notranslate"><span class="pre">__main__</span></code>module is present in <code class="xref py py-data docutils literal notranslate"><span class="pre">sys.modules</span></code>, Python passes that to <code class="docutils literal notranslate"><span class="pre">namely</span></code>.See <a class="reference internal" href="../reference/import.html#import-dunder-main"><span class="std std-ref">Special considerations for __main__</span></a> in theimport system’s reference for details on how this works.</p><p>The Python REPL is another example of a “top-level environment”, so anythingdefined in the REPL becomes part of the <code class="docutils literal notranslate"><span class="pre">__main__</span></code> scope:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">import</span><span class="w"> </span><span class="nn">namely</span><span class="gp">>>> </span><span class="n">namely</span><span class="o">.</span><span class="n">did_user_define_their_name</span><span class="p">()</span><span class="go">False</span><span class="gp">>>> </span><span class="n">namely</span><span class="o">.</span><span class="n">print_user_name</span><span class="p">()</span><span class="gt">Traceback (most recent call last):</span><span class="c">...</span><span class="gr">ValueError</span>: <span class="n">Define the variable `my_name`!</span><span class="gp">>>> </span><span class="n">my_name</span> <span class="o">=</span> <span class="s1">'Jabberwocky'</span><span class="gp">>>> </span><span class="n">namely</span><span class="o">.</span><span class="n">did_user_define_their_name</span><span class="p">()</span><span class="go">True</span><span class="gp">>>> </span><span class="n">namely</span><span class="o">.</span><span class="n">print_user_name</span><span class="p">()</span><span class="go">Jabberwocky</span></pre></div></div><p>The <code class="docutils literal notranslate"><span class="pre">__main__</span></code> scope is used in the implementation of <a class="reference internal" href="pdb.html#module-pdb" title="pdb: The Python debugger for interactive interpreters."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pdb</span></code></a> and<a class="reference internal" href="rlcompleter.html#module-rlcompleter" title="rlcompleter: Python identifier completion, suitable for the GNU readline library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">rlcompleter</span></code></a>.</p></section></section>
<div class="clearer"></div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="Main"> <div class="sphinxsidebarwrapper"> <div> <h3><a href="../contents.html">Table of Contents</a></h3> <ul><li><a class="reference internal" href="#"><code class="xref py py-mod docutils literal notranslate"><span class="pre">__main__</span></code> — Top-level code environment</a><ul><li><a class="reference internal" href="#name-main"><code class="docutils literal notranslate"><span class="pre">__name__</span> <span class="pre">==</span> <span class="pre">'__main__'</span></code></a><ul><li><a class="reference internal" href="#what-is-the-top-level-code-environment">What is the “top-level code environment”?</a></li><li><a class="reference internal" href="#idiomatic-usage">Idiomatic Usage</a></li><li><a class="reference internal" href="#packaging-considerations">Packaging Considerations</a></li></ul></li><li><a class="reference internal" href="#main-py-in-python-packages"><code class="docutils literal notranslate"><span class="pre">__main__.py</span></code> in Python Packages</a><ul><li><a class="reference internal" href="#id1">Idiomatic Usage</a></li></ul></li><li><a class="reference internal" href="#import-main"><code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">__main__</span></code></a></li></ul></li></ul>
</div> <div> <h4>Previous topic</h4> <p class="topless"><a href="builtins.html" title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">builtins</span></code> — Built-in objects</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="warnings.html" title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">warnings</span></code> — Warning control</a></p> </div> <script> document.addEventListener('DOMContentLoaded', () => { const title = document.querySelector('meta[property="og:title"]').content; const elements = document.querySelectorAll('.improvepage'); const pageurl = window.location.href.split('?')[0]; elements.forEach(element => { const url = new URL(element.href.split('?')[0].replace("-nojs", "")); url.searchParams.set('pagetitle', title); url.searchParams.set('pageurl', pageurl); url.searchParams.set('pagesource', "library/__main__.rst"); element.href = url.toString(); }); }); </script> <div role="note" aria-label="source link"> <h3>This page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a bug</a></li> <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li> <li> <a href="https://github.com/python/cpython/blob/main/Doc/library/__main__.rst?plain=1" rel="nofollow">Show source </a> </li> </ul> </div> </div><div id="sidebarbutton" title="Collapse sidebar"><span>«</span></div>
</div> <div class="clearer"></div> </div> <div class="related" role="navigation" aria-label="Related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="warnings.html" title="warnings — Warning control" >next</a> |</li> <li class="right" > <a href="builtins.html" title="builtins — Built-in objects" >previous</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.15.0a6 Documentation</a> » </li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="python.html" >Python Runtime Services</a> »</li> <li class="nav-item nav-item-this"><a href=""><code class="xref py py-mod docutils literal notranslate"><span class="pre">__main__</span></code> — Top-level code environment</a></li> <li class="right">
<div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box"> <input type="submit" value="Go"> </form> </div> | </li> <li class="right"><label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> |</li> </ul> </div> <div class="footer"> © <a href="../copyright.html">Copyright</a> 2001 Python Software Foundation. <br> This page is licensed under the Python Software Foundation License Version 2. <br> Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. <br> See <a href="/license.html">History and License</a> for more information.<br> <br>
The Python Software Foundation is a non-profit corporation.<a href="https://www.python.org/psf/donations/">Please donate.</a><br> <br> Last updated on Mar 10, 2026 (08:58 UTC). <a href="/bugs.html">Found a bug</a>? <br>
Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3. </div>
</body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553<!DOCTYPE html>
<html lang="en" data-content_root="../"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta property="og:title" content="_thread — Low-level threading API" /><meta property="og:type" content="website" /><meta property="og:url" content="https://docs.python.org/3/library/_thread.html" /><meta property="og:site_name" content="Python documentation" /><meta property="og:description" content="This module provides low-level primitives for working with multiple threads (also called light-weight processes or tasks) — multiple threads of control sharing their global data space. For synchron..." /><meta property="og:image:width" content="1146" /><meta property="og:image:height" content="600" /><meta property="og:image" content="https://docs.python.org/3.15/_images/social_previews/summary_library__thread_89ebfdf4.png" /><meta property="og:image:alt" content="This module provides low-level primitives for working with multiple threads (also called light-weight processes or tasks) — multiple threads of control sharing their global data space. For synchron..." /><meta name="description" content="This module provides low-level primitives for working with multiple threads (also called light-weight processes or tasks) — multiple threads of control sharing their global data space. For synchron..." /><meta name="twitter:card" content="summary_large_image" /><meta name="theme-color" content="#3776ab">
<title>_thread — Low-level threading API — Python 3.15.0a6 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" /> <link rel="stylesheet" type="text/css" href="../_static/classic.css?v=234b1a7c" /> <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=89a2f22a" /> <link rel="stylesheet" type="text/css" href="../_static/profiling-sampling-visualization.css?v=0c2600ae" /> <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" /> <script src="../_static/documentation_options.js?v=6b7c9ff5"></script> <script src="../_static/doctools.js?v=9bcbadda"></script> <script src="../_static/sphinx_highlight.js?v=dc90522c"></script> <script src="../_static/profiling-sampling-visualization.js?v=9811ed04"></script> <script src="../_static/sidebar.js"></script> <link rel="search" type="application/opensearchdescription+xml" title="Search within Python 3.15.0a6 documentation" href="../_static/opensearch.xml"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="copyright" title="Copyright" href="../copyright.html" /> <link rel="next" title="Networking and Interprocess Communication" href="ipc.html" /> <link rel="prev" title="contextvars — Context Variables" href="contextvars.html" /> <script defer file-types="bz2,epub,zip" data-domain="docs.python.org" src="https://analytics.python.org/js/script.file-downloads.outbound-links.js"></script> <link rel="canonical" href="https://docs.python.org/3/library/_thread.html">
<style> @media only screen { table.full-width-table { width: 100%; } } </style><link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css"> <link rel="shortcut icon" type="image/png" href="../_static/py.svg"> <script type="text/javascript" src="../_static/copybutton.js"></script> <script type="text/javascript" src="../_static/menu.js"></script> <script type="text/javascript" src="../_static/search-focus.js"></script> <script type="text/javascript" src="../_static/themetoggle.js"></script> <script type="text/javascript" src="../_static/rtd_switcher.js"></script> <meta name="readthedocs-addons-api-version" content="1">
</head><body><div class="mobile-nav"> <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation" aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu"> <nav class="nav-content" role="navigation"> <label for="menuToggler" class="toggler__label"> <span></span> </label> <span class="nav-items-wrapper"> <a href="https://www.python.org/" class="nav-logo"> <img src="../_static/py.svg" alt="Python logo"> </a> <span class="version_switcher_placeholder"></span> <form role="search" class="search" action="../search.html" method="get"> <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon"> <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> </svg> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q"> <input type="submit" value="Go"> </form> </span> </nav> <div class="menu-wrapper"> <nav class="menu" role="navigation" aria-label="main navigation"> <div class="language_switcher_placeholder"></div> <label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> <div> <h4>Previous topic</h4> <p class="topless"><a href="contextvars.html" title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">contextvars</span></code> — Context Variables</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="ipc.html" title="next chapter">Networking and Interprocess Communication</a></p> </div> <script> document.addEventListener('DOMContentLoaded', () => { const title = document.querySelector('meta[property="og:title"]').content; const elements = document.querySelectorAll('.improvepage'); const pageurl = window.location.href.split('?')[0]; elements.forEach(element => { const url = new URL(element.href.split('?')[0].replace("-nojs", "")); url.searchParams.set('pagetitle', title); url.searchParams.set('pageurl', pageurl); url.searchParams.set('pagesource', "library/_thread.rst"); element.href = url.toString(); }); }); </script> <div role="note" aria-label="source link"> <h3>This page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a bug</a></li> <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li> <li> <a href="https://github.com/python/cpython/blob/main/Doc/library/_thread.rst?plain=1" rel="nofollow">Show source </a> </li> </ul> </div> </nav> </div></div>
<div class="related" role="navigation" aria-label="Related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="ipc.html" title="Networking and Interprocess Communication" accesskey="N">next</a> |</li> <li class="right" > <a href="contextvars.html" title="contextvars — Context Variables" accesskey="P">previous</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.15.0a6 Documentation</a> » </li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="concurrency.html" accesskey="U">Concurrent Execution</a> »</li> <li class="nav-item nav-item-this"><a href=""><code class="xref py py-mod docutils literal notranslate"><span class="pre">_thread</span></code> — Low-level threading API</a></li> <li class="right">
<div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box"> <input type="submit" value="Go"> </form> </div> | </li> <li class="right"><label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> |</li> </ul> </div>
<div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <section id="module-_thread"><span id="thread-low-level-threading-api"></span><h1><code class="xref py py-mod docutils literal notranslate"><span class="pre">_thread</span></code> — Low-level threading API<a class="headerlink" href="#module-_thread" title="Link to this heading">¶</a></h1><hr class="docutils" id="index-0" /><p>This module provides low-level primitives for working with multiple threads(also called <em class="dfn">light-weight processes</em> or <em class="dfn">tasks</em>) — multiple threads ofcontrol sharing their global data space. For synchronization, simple locks(also called <em class="dfn">mutexes</em> or <em class="dfn">binary semaphores</em>) are provided.The <a class="reference internal" href="threading.html#module-threading" title="threading: Thread-based parallelism."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a> module provides an easier to use and higher-levelthreading API built on top of this module.</p><div class="versionchanged" id="index-1"><p><span class="versionmodified changed">Changed in version 3.7: </span>This module used to be optional, it is now always available.</p></div><p>This module defines the following constants and functions:</p><dl class="py exception"><dt class="sig sig-object py" id="thread.error"><em class="property"><span class="k"><span class="pre">exception</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">_thread.</span></span><span class="sig-name descname"><span class="pre">error</span></span><a class="headerlink" href="#thread.error" title="Link to this definition">¶</a></dt><dd><p>Raised on thread-specific errors.</p><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.3: </span>This is now a synonym of the built-in <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>.</p></div></dd></dl>
<dl class="py data"><dt class="sig sig-object py" id="thread.LockType"><span class="sig-prename descclassname"><span class="pre">_thread.</span></span><span class="sig-name descname"><span class="pre">LockType</span></span><a class="headerlink" href="#thread.LockType" title="Link to this definition">¶</a></dt><dd><p>This is the type of lock objects.</p></dd></dl>
<dl class="py function"><dt class="sig sig-object py" id="thread.start_new_thread"><span class="sig-prename descclassname"><span class="pre">_thread.</span></span><span class="sig-name descname"><span class="pre">start_new_thread</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">function</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">args</span></span></em><span class="optional">[</span>, <em class="sig-param"><span class="n"><span class="pre">kwargs</span></span></em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#thread.start_new_thread" title="Link to this definition">¶</a></dt><dd><p>Start a new thread and return its identifier. The thread executes thefunction <em>function</em> with the argument list <em>args</em> (which must be a tuple).The optional <em>kwargs</em> argument specifies a dictionary of keyword arguments.</p><p>When the function returns, the thread silently exits.</p><p>When the function terminates with an unhandled exception,<a class="reference internal" href="sys.html#sys.unraisablehook" title="sys.unraisablehook"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.unraisablehook()</span></code></a> is called to handle the exception. The <em>object</em>attribute of the hook argument is <em>function</em>. By default, a stack trace isprinted and then the thread exits (but other threads continue to run).</p><p>When the function raises a <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> exception, it is silentlyignored.</p><p class="audit-hook">Raises an <a class="reference internal" href="sys.html#auditing"><span class="std std-ref">auditing event</span></a> <code class="docutils literal notranslate"><span class="pre">_thread.start_new_thread</span></code> with arguments <code class="docutils literal notranslate"><span class="pre">function</span></code>, <code class="docutils literal notranslate"><span class="pre">args</span></code>, <code class="docutils literal notranslate"><span class="pre">kwargs</span></code>.</p><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.8: </span><a class="reference internal" href="sys.html#sys.unraisablehook" title="sys.unraisablehook"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.unraisablehook()</span></code></a> is now used to handle unhandled exceptions.</p></div></dd></dl>
<dl class="py function"><dt class="sig sig-object py" id="thread.interrupt_main"><span class="sig-prename descclassname"><span class="pre">_thread.</span></span><span class="sig-name descname"><span class="pre">interrupt_main</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">signum</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">signal.SIGINT</span></span></em>, <em class="sig-param"><span class="positional-only-separator o"><abbr title="Positional-only parameter separator (PEP 570)"><span class="pre">/</span></abbr></span></em><span class="sig-paren">)</span><a class="headerlink" href="#thread.interrupt_main" title="Link to this definition">¶</a></dt><dd><p>Simulate the effect of a signal arriving in the main thread.A thread can use this function to interrupt the main thread, thoughthere is no guarantee that the interruption will happen immediately.</p><p>If given, <em>signum</em> is the number of the signal to simulate.If <em>signum</em> is not given, <a class="reference internal" href="signal.html#signal.SIGINT" title="signal.SIGINT"><code class="xref py py-const docutils literal notranslate"><span class="pre">signal.SIGINT</span></code></a> is simulated.</p><p>If the given signal isn’t handled by Python (it was set to<a class="reference internal" href="signal.html#signal.SIG_DFL" title="signal.SIG_DFL"><code class="xref py py-const docutils literal notranslate"><span class="pre">signal.SIG_DFL</span></code></a> or <a class="reference internal" href="signal.html#signal.SIG_IGN" title="signal.SIG_IGN"><code class="xref py py-const docutils literal notranslate"><span class="pre">signal.SIG_IGN</span></code></a>), this function doesnothing.</p><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.10: </span>The <em>signum</em> argument is added to customize the signal number.</p></div><div class="admonition note"><p class="admonition-title">Note</p><p>This does not emit the corresponding signal but schedules a call tothe associated handler (if it exists).If you want to truly emit the signal, use <a class="reference internal" href="signal.html#signal.raise_signal" title="signal.raise_signal"><code class="xref py py-func docutils literal notranslate"><span class="pre">signal.raise_signal()</span></code></a>.</p></div></dd></dl>
<dl class="py function"><dt class="sig sig-object py" id="thread.exit"><span class="sig-prename descclassname"><span class="pre">_thread.</span></span><span class="sig-name descname"><span class="pre">exit</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#thread.exit" title="Link to this definition">¶</a></dt><dd><p>Raise the <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> exception. When not caught, this will cause thethread to exit silently.</p></dd></dl>
<dl class="py function"><dt class="sig sig-object py" id="thread.allocate_lock"><span class="sig-prename descclassname"><span class="pre">_thread.</span></span><span class="sig-name descname"><span class="pre">allocate_lock</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#thread.allocate_lock" title="Link to this definition">¶</a></dt><dd><p>Return a new lock object. Methods of locks are described below. The lock isinitially unlocked.</p></dd></dl>
<dl class="py function"><dt class="sig sig-object py" id="thread.get_ident"><span class="sig-prename descclassname"><span class="pre">_thread.</span></span><span class="sig-name descname"><span class="pre">get_ident</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#thread.get_ident" title="Link to this definition">¶</a></dt><dd><p>Return the ‘thread identifier’ of the current thread. This is a nonzerointeger. Its value has no direct meaning; it is intended as a magic cookie tobe used e.g. to index a dictionary of thread-specific data. Thread identifiersmay be recycled when a thread exits and another thread is created.</p></dd></dl>
<dl class="py function"><dt class="sig sig-object py" id="thread.get_native_id"><span class="sig-prename descclassname"><span class="pre">_thread.</span></span><span class="sig-name descname"><span class="pre">get_native_id</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#thread.get_native_id" title="Link to this definition">¶</a></dt><dd><p>Return the native integral Thread ID of the current thread assigned by the kernel.This is a non-negative integer.Its value may be used to uniquely identify this particular thread system-wide(until the thread terminates, after which the value may be recycled by the OS).</p><div class="availability docutils container"><p><a class="reference internal" href="intro.html#availability"><span class="std std-ref">Availability</span></a>: Windows, FreeBSD, Linux, macOS, OpenBSD, NetBSD, AIX, DragonFlyBSD, GNU/kFreeBSD, Solaris.</p></div><div class="versionadded"><p><span class="versionmodified added">Added in version 3.8.</span></p></div><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.13: </span>Added support for GNU/kFreeBSD.</p></div><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.15: </span>Added support for Solaris.</p></div></dd></dl>
<dl class="py function"><dt class="sig sig-object py" id="thread.stack_size"><span class="sig-prename descclassname"><span class="pre">_thread.</span></span><span class="sig-name descname"><span class="pre">stack_size</span></span><span class="sig-paren">(</span><span class="optional">[</span><em class="sig-param"><span class="n"><span class="pre">size</span></span></em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#thread.stack_size" title="Link to this definition">¶</a></dt><dd><p>Return the thread stack size used when creating new threads. The optional<em>size</em> argument specifies the stack size to be used for subsequently createdthreads, and must be 0 (use platform or configured default) or a positiveinteger value of at least 32,768 (32 KiB). If <em>size</em> is not specified,0 is used. If changing the thread stack size isunsupported, a <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 the specified stack size isinvalid, a <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> is raised and the stack size is unmodified. 32 KiBis currently the minimum supported stack size value to guarantee sufficientstack space for the interpreter itself. Note that some platforms may haveparticular restrictions on values for the stack size, such as requiring aminimum stack size > 32 KiB or requiring allocation in multiples of the systemmemory page size - platform documentation should be referred to for moreinformation (4 KiB pages are common; using multiples of 4096 for the stack size isthe suggested approach in the absence of more specific information).</p><div class="availability docutils container"><p><a class="reference internal" href="intro.html#availability"><span class="std std-ref">Availability</span></a>: Windows, pthreads.</p><p>Unix platforms with POSIX threads support.</p></div></dd></dl>
<dl class="py data"><dt class="sig sig-object py" id="thread.TIMEOUT_MAX"><span class="sig-prename descclassname"><span class="pre">_thread.</span></span><span class="sig-name descname"><span class="pre">TIMEOUT_MAX</span></span><a class="headerlink" href="#thread.TIMEOUT_MAX" title="Link to this definition">¶</a></dt><dd><p>The maximum value allowed for the <em>timeout</em> parameter of<a class="reference internal" href="threading.html#threading.Lock.acquire" title="threading.Lock.acquire"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Lock.acquire</span></code></a>. Specifying a timeout greaterthan this value will raise an <a class="reference internal" href="exceptions.html#OverflowError" title="OverflowError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowError</span></code></a>.</p><div class="versionadded"><p><span class="versionmodified added">Added in version 3.2.</span></p></div></dd></dl>
<p>Lock objects have the following methods:</p><dl class="py method"><dt class="sig sig-object py" id="thread.lock.acquire"><span class="sig-prename descclassname"><span class="pre">lock.</span></span><span class="sig-name descname"><span class="pre">acquire</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">blocking</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">True</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">-1</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#thread.lock.acquire" title="Link to this definition">¶</a></dt><dd><p>Without any optional argument, this method acquires the lock unconditionally, ifnecessary waiting until it is released by another thread (only one thread at atime can acquire a lock — that’s their reason for existence).</p><p>If the <em>blocking</em> argument is present, the action depends on itsvalue: if it is false, the lock is only acquired if it can be acquiredimmediately without waiting, while if it is true, the lock is acquiredunconditionally as above.</p><p>If the floating-point <em>timeout</em> argument is present and positive, itspecifies the maximum wait time in seconds before returning. A negative<em>timeout</em> argument specifies an unbounded wait. You cannot specifya <em>timeout</em> if <em>blocking</em> is false.</p><p>The return value is <code class="docutils literal notranslate"><span class="pre">True</span></code> if the lock is acquired successfully,<code class="docutils literal notranslate"><span class="pre">False</span></code> if not.</p><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.2: </span>The <em>timeout</em> parameter is new.</p></div><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.2: </span>Lock acquires can now be interrupted by signals on POSIX.</p></div><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.14: </span>Lock acquires can now be interrupted by signals on Windows.</p></div></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="thread.lock.release"><span class="sig-prename descclassname"><span class="pre">lock.</span></span><span class="sig-name descname"><span class="pre">release</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#thread.lock.release" title="Link to this definition">¶</a></dt><dd><p>Releases the lock. The lock must have been acquired earlier, but notnecessarily by the same thread.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="thread.lock.locked"><span class="sig-prename descclassname"><span class="pre">lock.</span></span><span class="sig-name descname"><span class="pre">locked</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#thread.lock.locked" title="Link to this definition">¶</a></dt><dd><p>Return the status of the lock: <code class="docutils literal notranslate"><span class="pre">True</span></code> if it has been acquired by some thread,<code class="docutils literal notranslate"><span class="pre">False</span></code> if not.</p></dd></dl>
<p>In addition to these methods, lock objects can also be used via the<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement, e.g.:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span><span class="w"> </span><span class="nn">_thread</span>
<span class="n">a_lock</span> <span class="o">=</span> <span class="n">_thread</span><span class="o">.</span><span class="n">allocate_lock</span><span class="p">()</span>
<span class="k">with</span> <span class="n">a_lock</span><span class="p">:</span> <span class="nb">print</span><span class="p">(</span><span class="s2">"a_lock is locked while this executes"</span><span class="p">)</span></pre></div></div><p><strong>Caveats:</strong></p><ul class="simple" id="index-2"><li><p>Interrupts always go to the main thread (the <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>exception will be received by that thread.)</p></li><li><p>Calling <a class="reference internal" href="sys.html#sys.exit" title="sys.exit"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exit()</span></code></a> or raising the <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> exception isequivalent to calling <a class="reference internal" href="#thread.exit" title="_thread.exit"><code class="xref py py-func docutils literal notranslate"><span class="pre">_thread.exit()</span></code></a>.</p></li><li><p>When the main thread exits, it is system defined whether the other threadssurvive. On most systems, they are killed without executing<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> … <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> clauses or executing objectdestructors.</p></li></ul></section>
<div class="clearer"></div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="Main"> <div class="sphinxsidebarwrapper"> <div> <h4>Previous topic</h4> <p class="topless"><a href="contextvars.html" title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">contextvars</span></code> — Context Variables</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="ipc.html" title="next chapter">Networking and Interprocess Communication</a></p> </div> <script> document.addEventListener('DOMContentLoaded', () => { const title = document.querySelector('meta[property="og:title"]').content; const elements = document.querySelectorAll('.improvepage'); const pageurl = window.location.href.split('?')[0]; elements.forEach(element => { const url = new URL(element.href.split('?')[0].replace("-nojs", "")); url.searchParams.set('pagetitle', title); url.searchParams.set('pageurl', pageurl); url.searchParams.set('pagesource', "library/_thread.rst"); element.href = url.toString(); }); }); </script> <div role="note" aria-label="source link"> <h3>This page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a bug</a></li> <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li> <li> <a href="https://github.com/python/cpython/blob/main/Doc/library/_thread.rst?plain=1" rel="nofollow">Show source </a> </li> </ul> </div> </div><div id="sidebarbutton" title="Collapse sidebar"><span>«</span></div>
</div> <div class="clearer"></div> </div> <div class="related" role="navigation" aria-label="Related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="ipc.html" title="Networking and Interprocess Communication" >next</a> |</li> <li class="right" > <a href="contextvars.html" title="contextvars — Context Variables" >previous</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.15.0a6 Documentation</a> » </li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="concurrency.html" >Concurrent Execution</a> »</li> <li class="nav-item nav-item-this"><a href=""><code class="xref py py-mod docutils literal notranslate"><span class="pre">_thread</span></code> — Low-level threading API</a></li> <li class="right">
<div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box"> <input type="submit" value="Go"> </form> </div> | </li> <li class="right"><label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> |</li> </ul> </div> <div class="footer"> © <a href="../copyright.html">Copyright</a> 2001 Python Software Foundation. <br> This page is licensed under the Python Software Foundation License Version 2. <br> Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. <br> See <a href="/license.html">History and License</a> for more information.<br> <br>
The Python Software Foundation is a non-profit corporation.<a href="https://www.python.org/psf/donations/">Please donate.</a><br> <br> Last updated on Mar 10, 2026 (08:58 UTC). <a href="/bugs.html">Found a bug</a>? <br>
Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3. </div>
</body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695<!DOCTYPE html>
<html lang="en" data-content_root="../"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta property="og:title" content="abc — Abstract Base Classes" /><meta property="og:type" content="website" /><meta property="og:url" content="https://docs.python.org/3/library/abc.html" /><meta property="og:site_name" content="Python documentation" /><meta property="og:description" content="Source code: Lib/abc.py This module provides the infrastructure for defining abstract base classes(ABCs) in Python, as outlined in PEP 3119; see the PEP for why this was added to Python. (See also ..." /><meta property="og:image:width" content="1146" /><meta property="og:image:height" content="600" /><meta property="og:image" content="https://docs.python.org/3.15/_images/social_previews/summary_library_abc_5b42805a.png" /><meta property="og:image:alt" content="Source code: Lib/abc.py This module provides the infrastructure for defining abstract base classes(ABCs) in Python, as outlined in PEP 3119; see the PEP for why this was added to Python. (See also ..." /><meta name="description" content="Source code: Lib/abc.py This module provides the infrastructure for defining abstract base classes(ABCs) in Python, as outlined in PEP 3119; see the PEP for why this was added to Python. (See also ..." /><meta name="twitter:card" content="summary_large_image" /><meta name="theme-color" content="#3776ab">
<title>abc — Abstract Base Classes — Python 3.15.0a6 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" /> <link rel="stylesheet" type="text/css" href="../_static/classic.css?v=234b1a7c" /> <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=89a2f22a" /> <link rel="stylesheet" type="text/css" href="../_static/profiling-sampling-visualization.css?v=0c2600ae" /> <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" /> <script src="../_static/documentation_options.js?v=6b7c9ff5"></script> <script src="../_static/doctools.js?v=9bcbadda"></script> <script src="../_static/sphinx_highlight.js?v=dc90522c"></script> <script src="../_static/profiling-sampling-visualization.js?v=9811ed04"></script> <script src="../_static/sidebar.js"></script> <link rel="search" type="application/opensearchdescription+xml" title="Search within Python 3.15.0a6 documentation" href="../_static/opensearch.xml"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="copyright" title="Copyright" href="../copyright.html" /> <link rel="next" title="atexit — Exit handlers" href="atexit.html" /> <link rel="prev" title="contextlib — Utilities for with-statement contexts" href="contextlib.html" /> <script defer file-types="bz2,epub,zip" data-domain="docs.python.org" src="https://analytics.python.org/js/script.file-downloads.outbound-links.js"></script> <link rel="canonical" href="https://docs.python.org/3/library/abc.html">
<style> @media only screen { table.full-width-table { width: 100%; } } </style><link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css"> <link rel="shortcut icon" type="image/png" href="../_static/py.svg"> <script type="text/javascript" src="../_static/copybutton.js"></script> <script type="text/javascript" src="../_static/menu.js"></script> <script type="text/javascript" src="../_static/search-focus.js"></script> <script type="text/javascript" src="../_static/themetoggle.js"></script> <script type="text/javascript" src="../_static/rtd_switcher.js"></script> <meta name="readthedocs-addons-api-version" content="1">
</head><body><div class="mobile-nav"> <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation" aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu"> <nav class="nav-content" role="navigation"> <label for="menuToggler" class="toggler__label"> <span></span> </label> <span class="nav-items-wrapper"> <a href="https://www.python.org/" class="nav-logo"> <img src="../_static/py.svg" alt="Python logo"> </a> <span class="version_switcher_placeholder"></span> <form role="search" class="search" action="../search.html" method="get"> <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon"> <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> </svg> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q"> <input type="submit" value="Go"> </form> </span> </nav> <div class="menu-wrapper"> <nav class="menu" role="navigation" aria-label="main navigation"> <div class="language_switcher_placeholder"></div> <label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> <div> <h4>Previous topic</h4> <p class="topless"><a href="contextlib.html" title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">contextlib</span></code> — Utilities for <code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code>-statement contexts</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="atexit.html" title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">atexit</span></code> — Exit handlers</a></p> </div> <script> document.addEventListener('DOMContentLoaded', () => { const title = document.querySelector('meta[property="og:title"]').content; const elements = document.querySelectorAll('.improvepage'); const pageurl = window.location.href.split('?')[0]; elements.forEach(element => { const url = new URL(element.href.split('?')[0].replace("-nojs", "")); url.searchParams.set('pagetitle', title); url.searchParams.set('pageurl', pageurl); url.searchParams.set('pagesource', "library/abc.rst"); element.href = url.toString(); }); }); </script> <div role="note" aria-label="source link"> <h3>This page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a bug</a></li> <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li> <li> <a href="https://github.com/python/cpython/blob/main/Doc/library/abc.rst?plain=1" rel="nofollow">Show source </a> </li> </ul> </div> </nav> </div></div>
<div class="related" role="navigation" aria-label="Related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="atexit.html" title="atexit — Exit handlers" accesskey="N">next</a> |</li> <li class="right" > <a href="contextlib.html" title="contextlib — Utilities for with-statement contexts" accesskey="P">previous</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.15.0a6 Documentation</a> » </li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="python.html" accesskey="U">Python Runtime Services</a> »</li> <li class="nav-item nav-item-this"><a href=""><code class="xref py py-mod docutils literal notranslate"><span class="pre">abc</span></code> — Abstract Base Classes</a></li> <li class="right">
<div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box"> <input type="submit" value="Go"> </form> </div> | </li> <li class="right"><label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> |</li> </ul> </div>
<div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <section id="module-abc"><span id="abc-abstract-base-classes"></span><h1><code class="xref py py-mod docutils literal notranslate"><span class="pre">abc</span></code> — Abstract Base Classes<a class="headerlink" href="#module-abc" title="Link to this heading">¶</a></h1><p><strong>Source code:</strong> <a class="extlink-source reference external" href="https://github.com/python/cpython/tree/main/Lib/abc.py">Lib/abc.py</a></p><hr class="docutils" /><p>This module provides the infrastructure for defining <a class="reference internal" href="../glossary.html#term-abstract-base-class"><span class="xref std std-term">abstract baseclasses</span></a> (ABCs) in Python, as outlined in <span class="target" id="index-0"></span><a class="pep reference external" href="https://peps.python.org/pep-3119/"><strong>PEP 3119</strong></a>;see the PEP for why this was added to Python. (See also <span class="target" id="index-1"></span><a class="pep reference external" href="https://peps.python.org/pep-3141/"><strong>PEP 3141</strong></a> and the<a class="reference internal" href="numbers.html#module-numbers" title="numbers: Numeric abstract base classes (Complex, Real, Integral, etc.)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">numbers</span></code></a> module regarding a type hierarchy for numbers based on ABCs.)</p><p>The <a class="reference internal" href="collections.html#module-collections" title="collections: Container datatypes"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections</span></code></a> module has some concrete classes that derive fromABCs; these can, of course, be further derived. In addition, the<a class="reference internal" href="collections.abc.html#module-collections.abc" title="collections.abc: Abstract base classes for containers"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections.abc</span></code></a> submodule has some ABCs that can be used to test whethera class or instance provides a particular interface, for example, if it is<a class="reference internal" href="../glossary.html#term-hashable"><span class="xref std std-term">hashable</span></a> or if it is a <a class="reference internal" href="../glossary.html#term-mapping"><span class="xref std std-term">mapping</span></a>.</p><p>This module provides the metaclass <a class="reference internal" href="#abc.ABCMeta" title="abc.ABCMeta"><code class="xref py py-class docutils literal notranslate"><span class="pre">ABCMeta</span></code></a> for defining ABCs anda helper class <a class="reference internal" href="#abc.ABC" title="abc.ABC"><code class="xref py py-class docutils literal notranslate"><span class="pre">ABC</span></code></a> to alternatively define ABCs through inheritance:</p><dl class="py class"><dt class="sig sig-object py" id="abc.ABC"><em class="property"><span class="k"><span class="pre">class</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">abc.</span></span><span class="sig-name descname"><span class="pre">ABC</span></span><a class="headerlink" href="#abc.ABC" title="Link to this definition">¶</a></dt><dd><p>A helper class that has <a class="reference internal" href="#abc.ABCMeta" title="abc.ABCMeta"><code class="xref py py-class docutils literal notranslate"><span class="pre">ABCMeta</span></code></a> as its metaclass. With this class,an abstract base class can be created by simply deriving from <code class="xref py py-class docutils literal notranslate"><span class="pre">ABC</span></code>avoiding sometimes confusing metaclass usage, for example:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span><span class="w"> </span><span class="nn">abc</span><span class="w"> </span><span class="kn">import</span> <span class="n">ABC</span>
<span class="k">class</span><span class="w"> </span><span class="nc">MyABC</span><span class="p">(</span><span class="n">ABC</span><span class="p">):</span> <span class="k">pass</span></pre></div></div><p>Note that the type of <code class="xref py py-class docutils literal notranslate"><span class="pre">ABC</span></code> is still <a class="reference internal" href="#abc.ABCMeta" title="abc.ABCMeta"><code class="xref py py-class docutils literal notranslate"><span class="pre">ABCMeta</span></code></a>, thereforeinheriting from <code class="xref py py-class docutils literal notranslate"><span class="pre">ABC</span></code> requires the usual precautions regardingmetaclass usage, as multiple inheritance may lead to metaclass conflicts.One may also define an abstract base class by passing the metaclasskeyword and using <code class="xref py py-class docutils literal notranslate"><span class="pre">ABCMeta</span></code> directly, for example:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span><span class="w"> </span><span class="nn">abc</span><span class="w"> </span><span class="kn">import</span> <span class="n">ABCMeta</span>
<span class="k">class</span><span class="w"> </span><span class="nc">MyABC</span><span class="p">(</span><span class="n">metaclass</span><span class="o">=</span><span class="n">ABCMeta</span><span class="p">):</span> <span class="k">pass</span></pre></div></div><div class="versionadded"><p><span class="versionmodified added">Added in version 3.4.</span></p></div></dd></dl>
<dl class="py class"><dt class="sig sig-object py" id="abc.ABCMeta"><em class="property"><span class="k"><span class="pre">class</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">abc.</span></span><span class="sig-name descname"><span class="pre">ABCMeta</span></span><a class="headerlink" href="#abc.ABCMeta" title="Link to this definition">¶</a></dt><dd><p>Metaclass for defining Abstract Base Classes (ABCs).</p><p>Use this metaclass to create an ABC. An ABC can be subclassed directly, andthen acts as a mix-in class. You can also register unrelated concreteclasses (even built-in classes) and unrelated ABCs as “virtual subclasses” –these and their descendants will be considered subclasses of the registeringABC by the built-in <a class="reference internal" href="functions.html#issubclass" title="issubclass"><code class="xref py py-func docutils literal notranslate"><span class="pre">issubclass()</span></code></a> function, but the registering ABCwon’t show up in their MRO (Method Resolution Order) nor will methodimplementations defined by the registering ABC be callable (not even via<a class="reference internal" href="functions.html#super" title="super"><code class="xref py py-func docutils literal notranslate"><span class="pre">super()</span></code></a>). <a class="footnote-reference brackets" href="#id2" id="id1" role="doc-noteref"><span class="fn-bracket">[</span>1<span class="fn-bracket">]</span></a></p><p>Classes created with a metaclass of <code class="xref py py-class docutils literal notranslate"><span class="pre">ABCMeta</span></code> have the following method:</p><dl class="py method"><dt class="sig sig-object py" id="abc.ABCMeta.register"><span class="sig-name descname"><span class="pre">register</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">subclass</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#abc.ABCMeta.register" title="Link to this definition">¶</a></dt><dd><p>Register <em>subclass</em> as a “virtual subclass” of this ABC. Forexample:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span><span class="w"> </span><span class="nn">abc</span><span class="w"> </span><span class="kn">import</span> <span class="n">ABC</span>
<span class="k">class</span><span class="w"> </span><span class="nc">MyABC</span><span class="p">(</span><span class="n">ABC</span><span class="p">):</span> <span class="k">pass</span>
<span class="n">MyABC</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="nb">tuple</span><span class="p">)</span>
<span class="k">assert</span> <span class="nb">issubclass</span><span class="p">(</span><span class="nb">tuple</span><span class="p">,</span> <span class="n">MyABC</span><span class="p">)</span><span class="k">assert</span> <span class="nb">isinstance</span><span class="p">((),</span> <span class="n">MyABC</span><span class="p">)</span></pre></div></div><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.3: </span>Returns the registered subclass, to allow usage as a class decorator.</p></div><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.4: </span>To detect calls to <code class="xref py py-meth docutils literal notranslate"><span class="pre">register()</span></code>, you can use the<a class="reference internal" href="#abc.get_cache_token" title="abc.get_cache_token"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_cache_token()</span></code></a> function.</p></div></dd></dl>
<p>You can also override this method in an abstract base class:</p><dl class="py method"><dt class="sig sig-object py" id="abc.ABCMeta.__subclasshook__"><span class="sig-name descname"><span class="pre">__subclasshook__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">subclass</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#abc.ABCMeta.__subclasshook__" title="Link to this definition">¶</a></dt><dd><p>(Must be defined as a class method.)</p><p>Check whether <em>subclass</em> is considered a subclass of this ABC. This meansthat you can customize the behavior of <a class="reference internal" href="functions.html#issubclass" title="issubclass"><code class="xref py py-func docutils literal notranslate"><span class="pre">issubclass()</span></code></a> further without theneed to call <a class="reference internal" href="#abc.ABCMeta.register" title="abc.ABCMeta.register"><code class="xref py py-meth docutils literal notranslate"><span class="pre">register()</span></code></a> on every class you want to consider asubclass of the ABC. (This class method is called from the<a class="reference internal" href="../reference/datamodel.html#type.__subclasscheck__" title="type.__subclasscheck__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__subclasscheck__()</span></code></a> method of the ABC.)</p><p>This method should return <code class="docutils literal notranslate"><span class="pre">True</span></code>, <code class="docutils literal notranslate"><span class="pre">False</span></code> or <a class="reference internal" href="constants.html#NotImplemented" title="NotImplemented"><code class="xref py py-data docutils literal notranslate"><span class="pre">NotImplemented</span></code></a>. Ifit returns <code class="docutils literal notranslate"><span class="pre">True</span></code>, the <em>subclass</em> is considered a subclass of this ABC.If it returns <code class="docutils literal notranslate"><span class="pre">False</span></code>, the <em>subclass</em> is not considered a subclass ofthis ABC, even if it would normally be one. If it returns<code class="xref py py-data docutils literal notranslate"><span class="pre">NotImplemented</span></code>, the subclass check is continued with the usualmechanism.</p></dd></dl>
<p>For a demonstration of these concepts, look at this example ABC definition:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span><span class="w"> </span><span class="nc">Foo</span><span class="p">:</span> <span class="k">def</span><span class="w"> </span><span class="fm">__getitem__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">index</span><span class="p">):</span> <span class="o">...</span> <span class="k">def</span><span class="w"> </span><span class="fm">__len__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="o">...</span> <span class="k">def</span><span class="w"> </span><span class="nf">get_iterator</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">return</span> <span class="nb">iter</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
<span class="k">class</span><span class="w"> </span><span class="nc">MyIterable</span><span class="p">(</span><span class="n">ABC</span><span class="p">):</span>
<span class="nd">@abstractmethod</span> <span class="k">def</span><span class="w"> </span><span class="fm">__iter__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">while</span> <span class="kc">False</span><span class="p">:</span> <span class="k">yield</span> <span class="kc">None</span>
<span class="k">def</span><span class="w"> </span><span class="nf">get_iterator</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="fm">__iter__</span><span class="p">()</span>
<span class="nd">@classmethod</span> <span class="k">def</span><span class="w"> </span><span class="nf">__subclasshook__</span><span class="p">(</span><span class="bp">cls</span><span class="p">,</span> <span class="n">C</span><span class="p">):</span> <span class="k">if</span> <span class="bp">cls</span> <span class="ow">is</span> <span class="n">MyIterable</span><span class="p">:</span> <span class="k">if</span> <span class="nb">any</span><span class="p">(</span><span class="s2">"__iter__"</span> <span class="ow">in</span> <span class="n">B</span><span class="o">.</span><span class="vm">__dict__</span> <span class="k">for</span> <span class="n">B</span> <span class="ow">in</span> <span class="n">C</span><span class="o">.</span><span class="vm">__mro__</span><span class="p">):</span> <span class="k">return</span> <span class="kc">True</span> <span class="k">return</span> <span class="bp">NotImplemented</span>
<span class="n">MyIterable</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="n">Foo</span><span class="p">)</span></pre></div></div><p>The ABC <code class="docutils literal notranslate"><span class="pre">MyIterable</span></code> defines the standard iterable method,<a class="reference internal" href="../reference/datamodel.html#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a>, as an abstract method. The implementation givenhere can still be called from subclasses. The <code class="xref py py-meth docutils literal notranslate"><span class="pre">get_iterator()</span></code> methodis also part of the <code class="docutils literal notranslate"><span class="pre">MyIterable</span></code> abstract base class, but it does not haveto be overridden in non-abstract derived classes.</p><p>The <a class="reference internal" href="#abc.ABCMeta.__subclasshook__" title="abc.ABCMeta.__subclasshook__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__subclasshook__()</span></code></a> class method defined here says that any classthat has an <a class="reference internal" href="../reference/datamodel.html#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a> method in its<a class="reference internal" href="../reference/datamodel.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> (or in that of one of its base classes, accessedvia the <a class="reference internal" href="../reference/datamodel.html#type.__mro__" title="type.__mro__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__mro__</span></code></a> list) is considered a <code class="docutils literal notranslate"><span class="pre">MyIterable</span></code> too.</p><p>Finally, the last line makes <code class="docutils literal notranslate"><span class="pre">Foo</span></code> a virtual subclass of <code class="docutils literal notranslate"><span class="pre">MyIterable</span></code>,even though it does not define an <a class="reference internal" href="../reference/datamodel.html#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a> method (it usesthe old-style iterable protocol, defined in terms of <a class="reference internal" href="../reference/datamodel.html#object.__len__" title="object.__len__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__len__()</span></code></a> and<a class="reference internal" href="../reference/datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>). Note that this will not make <code class="docutils literal notranslate"><span class="pre">get_iterator</span></code>available as a method of <code class="docutils literal notranslate"><span class="pre">Foo</span></code>, so it is provided separately.</p></dd></dl>
<p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">abc</span></code> module also provides the following decorator:</p><dl class="py function"><dt class="sig sig-object py" id="abc.abstractmethod"><span class="sig-prename descclassname"><span class="pre">@</span></span><span class="sig-prename descclassname"><span class="pre">abc.</span></span><span class="sig-name descname"><span class="pre">abstractmethod</span></span><a class="headerlink" href="#abc.abstractmethod" title="Link to this definition">¶</a></dt><dd><p>A decorator indicating abstract methods.</p><p>Using this decorator requires that the class’s metaclass is <a class="reference internal" href="#abc.ABCMeta" title="abc.ABCMeta"><code class="xref py py-class docutils literal notranslate"><span class="pre">ABCMeta</span></code></a>or is derived from it. A class that has a metaclass derived from<code class="xref py py-class docutils literal notranslate"><span class="pre">ABCMeta</span></code> cannot be instantiated unless all of its abstract methodsand properties are overridden. The abstract methods can be called using anyof the normal ‘super’ call mechanisms. <code class="xref py py-func docutils literal notranslate"><span class="pre">abstractmethod()</span></code> may be usedto declare abstract methods for properties and descriptors.</p><p>Dynamically adding abstract methods to a class, or attempting to modify theabstraction status of a method or class once it is created, are onlysupported using the <a class="reference internal" href="#abc.update_abstractmethods" title="abc.update_abstractmethods"><code class="xref py py-func docutils literal notranslate"><span class="pre">update_abstractmethods()</span></code></a> function. The<code class="xref py py-func docutils literal notranslate"><span class="pre">abstractmethod()</span></code> only affects subclasses derived using regularinheritance; “virtual subclasses” registered with the ABC’s<a class="reference internal" href="#abc.ABCMeta.register" title="abc.ABCMeta.register"><code class="xref py py-meth docutils literal notranslate"><span class="pre">register()</span></code></a> method are not affected.</p><p>When <code class="xref py py-func docutils literal notranslate"><span class="pre">abstractmethod()</span></code> is applied in combination with other methoddescriptors, it should be applied as the innermost decorator, as shown inthe following usage examples:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span><span class="w"> </span><span class="nc">C</span><span class="p">(</span><span class="n">ABC</span><span class="p">):</span> <span class="nd">@abstractmethod</span> <span class="k">def</span><span class="w"> </span><span class="nf">my_abstract_method</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">arg1</span><span class="p">):</span> <span class="o">...</span> <span class="nd">@classmethod</span> <span class="nd">@abstractmethod</span> <span class="k">def</span><span class="w"> </span><span class="nf">my_abstract_classmethod</span><span class="p">(</span><span class="bp">cls</span><span class="p">,</span> <span class="n">arg2</span><span class="p">):</span> <span class="o">...</span> <span class="nd">@staticmethod</span> <span class="nd">@abstractmethod</span> <span class="k">def</span><span class="w"> </span><span class="nf">my_abstract_staticmethod</span><span class="p">(</span><span class="n">arg3</span><span class="p">):</span> <span class="o">...</span>
<span class="nd">@property</span> <span class="nd">@abstractmethod</span> <span class="k">def</span><span class="w"> </span><span class="nf">my_abstract_property</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="o">...</span> <span class="nd">@my_abstract_property</span><span class="o">.</span><span class="n">setter</span> <span class="nd">@abstractmethod</span> <span class="k">def</span><span class="w"> </span><span class="nf">my_abstract_property</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">val</span><span class="p">):</span> <span class="o">...</span>
<span class="nd">@abstractmethod</span> <span class="k">def</span><span class="w"> </span><span class="nf">_get_x</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="o">...</span> <span class="nd">@abstractmethod</span> <span class="k">def</span><span class="w"> </span><span class="nf">_set_x</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">val</span><span class="p">):</span> <span class="o">...</span> <span class="n">x</span> <span class="o">=</span> <span class="nb">property</span><span class="p">(</span><span class="n">_get_x</span><span class="p">,</span> <span class="n">_set_x</span><span class="p">)</span></pre></div></div><p>In order to correctly interoperate with the abstract base class machinery,the descriptor must identify itself as abstract using<code class="xref py py-attr docutils literal notranslate"><span class="pre">__isabstractmethod__</span></code>. In general, this attribute should be <code class="docutils literal notranslate"><span class="pre">True</span></code>if any of the methods used to compose the descriptor are abstract. Forexample, Python’s built-in <a class="reference internal" href="functions.html#property" title="property"><code class="xref py py-class docutils literal notranslate"><span class="pre">property</span></code></a> does the equivalent of:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span><span class="w"> </span><span class="nc">Descriptor</span><span class="p">:</span> <span class="o">...</span> <span class="nd">@property</span> <span class="k">def</span><span class="w"> </span><span class="nf">__isabstractmethod__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">return</span> <span class="nb">any</span><span class="p">(</span><span class="nb">getattr</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="s1">'__isabstractmethod__'</span><span class="p">,</span> <span class="kc">False</span><span class="p">)</span> <span class="k">for</span> <span class="n">f</span> <span class="ow">in</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">_fget</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">_fset</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">_fdel</span><span class="p">))</span></pre></div></div><div class="admonition note"><p class="admonition-title">Note</p><p>Unlike Java abstract methods, these abstractmethods may have an implementation. This implementation can becalled via the <a class="reference internal" href="functions.html#super" title="super"><code class="xref py py-func docutils literal notranslate"><span class="pre">super()</span></code></a> mechanism from the class thatoverrides it. This could be useful as an end-point for asuper-call in a framework that uses cooperativemultiple-inheritance.</p></div></dd></dl>
<p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">abc</span></code> module also supports the following legacy decorators:</p><dl class="py function"><dt class="sig sig-object py" id="abc.abstractclassmethod"><span class="sig-prename descclassname"><span class="pre">@</span></span><span class="sig-prename descclassname"><span class="pre">abc.</span></span><span class="sig-name descname"><span class="pre">abstractclassmethod</span></span><a class="headerlink" href="#abc.abstractclassmethod" title="Link to this definition">¶</a></dt><dd><div class="versionadded"><p><span class="versionmodified added">Added in version 3.2.</span></p></div><div class="deprecated"><p><span class="versionmodified deprecated">Deprecated since version 3.3: </span>It is now possible to use <a class="reference internal" href="functions.html#classmethod" title="classmethod"><code class="xref py py-class docutils literal notranslate"><span class="pre">classmethod</span></code></a> with<a class="reference internal" href="#abc.abstractmethod" title="abc.abstractmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">abstractmethod()</span></code></a>, making this decorator redundant.</p></div><p>A subclass of the built-in <a class="reference internal" href="functions.html#classmethod" title="classmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">classmethod()</span></code></a>, indicating an abstractclassmethod. Otherwise it is similar to <a class="reference internal" href="#abc.abstractmethod" title="abc.abstractmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">abstractmethod()</span></code></a>.</p><p>This special case is deprecated, as the <a class="reference internal" href="functions.html#classmethod" title="classmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">classmethod()</span></code></a> decoratoris now correctly identified as abstract when applied to an abstractmethod:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span><span class="w"> </span><span class="nc">C</span><span class="p">(</span><span class="n">ABC</span><span class="p">):</span> <span class="nd">@classmethod</span> <span class="nd">@abstractmethod</span> <span class="k">def</span><span class="w"> </span><span class="nf">my_abstract_classmethod</span><span class="p">(</span><span class="bp">cls</span><span class="p">,</span> <span class="n">arg</span><span class="p">):</span> <span class="o">...</span></pre></div></div></dd></dl>
<dl class="py function"><dt class="sig sig-object py" id="abc.abstractstaticmethod"><span class="sig-prename descclassname"><span class="pre">@</span></span><span class="sig-prename descclassname"><span class="pre">abc.</span></span><span class="sig-name descname"><span class="pre">abstractstaticmethod</span></span><a class="headerlink" href="#abc.abstractstaticmethod" title="Link to this definition">¶</a></dt><dd><div class="versionadded"><p><span class="versionmodified added">Added in version 3.2.</span></p></div><div class="deprecated"><p><span class="versionmodified deprecated">Deprecated since version 3.3: </span>It is now possible to use <a class="reference internal" href="functions.html#staticmethod" title="staticmethod"><code class="xref py py-class docutils literal notranslate"><span class="pre">staticmethod</span></code></a> with<a class="reference internal" href="#abc.abstractmethod" title="abc.abstractmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">abstractmethod()</span></code></a>, making this decorator redundant.</p></div><p>A subclass of the built-in <a class="reference internal" href="functions.html#staticmethod" title="staticmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">staticmethod()</span></code></a>, indicating an abstractstaticmethod. Otherwise it is similar to <a class="reference internal" href="#abc.abstractmethod" title="abc.abstractmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">abstractmethod()</span></code></a>.</p><p>This special case is deprecated, as the <a class="reference internal" href="functions.html#staticmethod" title="staticmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">staticmethod()</span></code></a> decoratoris now correctly identified as abstract when applied to an abstractmethod:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span><span class="w"> </span><span class="nc">C</span><span class="p">(</span><span class="n">ABC</span><span class="p">):</span> <span class="nd">@staticmethod</span> <span class="nd">@abstractmethod</span> <span class="k">def</span><span class="w"> </span><span class="nf">my_abstract_staticmethod</span><span class="p">(</span><span class="n">arg</span><span class="p">):</span> <span class="o">...</span></pre></div></div></dd></dl>
<dl class="py function"><dt class="sig sig-object py" id="abc.abstractproperty"><span class="sig-prename descclassname"><span class="pre">@</span></span><span class="sig-prename descclassname"><span class="pre">abc.</span></span><span class="sig-name descname"><span class="pre">abstractproperty</span></span><a class="headerlink" href="#abc.abstractproperty" title="Link to this definition">¶</a></dt><dd><div class="deprecated"><p><span class="versionmodified deprecated">Deprecated since version 3.3: </span>It is now possible to use <a class="reference internal" href="functions.html#property" title="property"><code class="xref py py-class docutils literal notranslate"><span class="pre">property</span></code></a>, <a class="reference internal" href="functions.html#property.getter" title="property.getter"><code class="xref py py-meth docutils literal notranslate"><span class="pre">property.getter()</span></code></a>,<a class="reference internal" href="functions.html#property.setter" title="property.setter"><code class="xref py py-meth docutils literal notranslate"><span class="pre">property.setter()</span></code></a> and <a class="reference internal" href="functions.html#property.deleter" title="property.deleter"><code class="xref py py-meth docutils literal notranslate"><span class="pre">property.deleter()</span></code></a> with<a class="reference internal" href="#abc.abstractmethod" title="abc.abstractmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">abstractmethod()</span></code></a>, making this decorator redundant.</p></div><p>A subclass of the built-in <a class="reference internal" href="functions.html#property" title="property"><code class="xref py py-func docutils literal notranslate"><span class="pre">property()</span></code></a>, indicating an abstractproperty.</p><p>This special case is deprecated, as the <a class="reference internal" href="functions.html#property" title="property"><code class="xref py py-func docutils literal notranslate"><span class="pre">property()</span></code></a> decoratoris now correctly identified as abstract when applied to an abstractmethod:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span><span class="w"> </span><span class="nc">C</span><span class="p">(</span><span class="n">ABC</span><span class="p">):</span> <span class="nd">@property</span> <span class="nd">@abstractmethod</span> <span class="k">def</span><span class="w"> </span><span class="nf">my_abstract_property</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="o">...</span></pre></div></div><p>The above example defines a read-only property; you can also define aread-write abstract property by appropriately marking one or more of theunderlying methods as abstract:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span><span class="w"> </span><span class="nc">C</span><span class="p">(</span><span class="n">ABC</span><span class="p">):</span> <span class="nd">@property</span> <span class="k">def</span><span class="w"> </span><span class="nf">x</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="o">...</span>
<span class="nd">@x</span><span class="o">.</span><span class="n">setter</span> <span class="nd">@abstractmethod</span> <span class="k">def</span><span class="w"> </span><span class="nf">x</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">val</span><span class="p">):</span> <span class="o">...</span></pre></div></div><p>If only some components are abstract, only those components need to beupdated to create a concrete property in a subclass:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span><span class="w"> </span><span class="nc">D</span><span class="p">(</span><span class="n">C</span><span class="p">):</span> <span class="nd">@C</span><span class="o">.</span><span class="n">x</span><span class="o">.</span><span class="n">setter</span> <span class="k">def</span><span class="w"> </span><span class="nf">x</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">val</span><span class="p">):</span> <span class="o">...</span></pre></div></div></dd></dl>
<p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">abc</span></code> module also provides the following functions:</p><dl class="py function"><dt class="sig sig-object py" id="abc.get_cache_token"><span class="sig-prename descclassname"><span class="pre">abc.</span></span><span class="sig-name descname"><span class="pre">get_cache_token</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#abc.get_cache_token" title="Link to this definition">¶</a></dt><dd><p>Returns the current abstract base class cache token.</p><p>The token is an opaque object (that supports equality testing) identifyingthe current version of the abstract base class cache for virtual subclasses.The token changes with every call to <a class="reference internal" href="#abc.ABCMeta.register" title="abc.ABCMeta.register"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ABCMeta.register()</span></code></a> on any ABC.</p><div class="versionadded"><p><span class="versionmodified added">Added in version 3.4.</span></p></div></dd></dl>
<dl class="py function"><dt class="sig sig-object py" id="abc.update_abstractmethods"><span class="sig-prename descclassname"><span class="pre">abc.</span></span><span class="sig-name descname"><span class="pre">update_abstractmethods</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">cls</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#abc.update_abstractmethods" title="Link to this definition">¶</a></dt><dd><p>A function to recalculate an abstract class’s abstraction status. Thisfunction should be called if a class’s abstract methods have beenimplemented or changed after it was created. Usually, this function shouldbe called from within a class decorator.</p><p>Returns <em>cls</em>, to allow usage as a class decorator.</p><p>If <em>cls</em> is not an instance of <a class="reference internal" href="#abc.ABCMeta" title="abc.ABCMeta"><code class="xref py py-class docutils literal notranslate"><span class="pre">ABCMeta</span></code></a>, does nothing.</p><div class="admonition note"><p class="admonition-title">Note</p><p>This function assumes that <em>cls</em>’s superclasses are already updated.It does not update any subclasses.</p></div><div class="versionadded"><p><span class="versionmodified added">Added in version 3.10.</span></p></div></dd></dl>
<p class="rubric">Footnotes</p><aside class="footnote-list brackets"><aside class="footnote brackets" id="id2" role="doc-footnote"><span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id1">1</a><span class="fn-bracket">]</span></span><p>C++ programmers should note that Python’s virtual base classconcept is not the same as C++’s.</p></aside></aside></section>
<div class="clearer"></div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="Main"> <div class="sphinxsidebarwrapper"> <div> <h4>Previous topic</h4> <p class="topless"><a href="contextlib.html" title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">contextlib</span></code> — Utilities for <code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code>-statement contexts</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="atexit.html" title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">atexit</span></code> — Exit handlers</a></p> </div> <script> document.addEventListener('DOMContentLoaded', () => { const title = document.querySelector('meta[property="og:title"]').content; const elements = document.querySelectorAll('.improvepage'); const pageurl = window.location.href.split('?')[0]; elements.forEach(element => { const url = new URL(element.href.split('?')[0].replace("-nojs", "")); url.searchParams.set('pagetitle', title); url.searchParams.set('pageurl', pageurl); url.searchParams.set('pagesource', "library/abc.rst"); element.href = url.toString(); }); }); </script> <div role="note" aria-label="source link"> <h3>This page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a bug</a></li> <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li> <li> <a href="https://github.com/python/cpython/blob/main/Doc/library/abc.rst?plain=1" rel="nofollow">Show source </a> </li> </ul> </div> </div><div id="sidebarbutton" title="Collapse sidebar"><span>«</span></div>
</div> <div class="clearer"></div> </div> <div class="related" role="navigation" aria-label="Related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="atexit.html" title="atexit — Exit handlers" >next</a> |</li> <li class="right" > <a href="contextlib.html" title="contextlib — Utilities for with-statement contexts" >previous</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.15.0a6 Documentation</a> » </li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="python.html" >Python Runtime Services</a> »</li> <li class="nav-item nav-item-this"><a href=""><code class="xref py py-mod docutils literal notranslate"><span class="pre">abc</span></code> — Abstract Base Classes</a></li> <li class="right">
<div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box"> <input type="submit" value="Go"> </form> </div> | </li> <li class="right"><label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> |</li> </ul> </div> <div class="footer"> © <a href="../copyright.html">Copyright</a> 2001 Python Software Foundation. <br> This page is licensed under the Python Software Foundation License Version 2. <br> Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. <br> See <a href="/license.html">History and License</a> for more information.<br> <br>
The Python Software Foundation is a non-profit corporation.<a href="https://www.python.org/psf/donations/">Please donate.</a><br> <br> Last updated on Mar 10, 2026 (08:58 UTC). <a href="/bugs.html">Found a bug</a>? <br>
Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3. </div>
</body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353<!DOCTYPE html>
<html lang="en" data-content_root="../"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta property="og:title" content="aifc — Read and write AIFF and AIFC files" /><meta property="og:type" content="website" /><meta property="og:url" content="https://docs.python.org/3/library/aifc.html" /><meta property="og:site_name" content="Python documentation" /><meta property="og:description" content="This module is no longer part of the Python standard library. It was removed in Python 3.13 after being deprecated in Python 3.11. The removal was decided in PEP 594. The last version of Python tha..." /><meta property="og:image:width" content="1146" /><meta property="og:image:height" content="600" /><meta property="og:image" content="https://docs.python.org/3.15/_images/social_previews/summary_library_aifc_e09a081d.png" /><meta property="og:image:alt" content="This module is no longer part of the Python standard library. It was removed in Python 3.13 after being deprecated in Python 3.11. The removal was decided in PEP 594. The last version of Python tha..." /><meta name="description" content="This module is no longer part of the Python standard library. It was removed in Python 3.13 after being deprecated in Python 3.11. The removal was decided in PEP 594. The last version of Python tha..." /><meta name="twitter:card" content="summary_large_image" /><meta name="theme-color" content="#3776ab">
<title>aifc — Read and write AIFF and AIFC files — Python 3.15.0a6 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" /> <link rel="stylesheet" type="text/css" href="../_static/classic.css?v=234b1a7c" /> <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=89a2f22a" /> <link rel="stylesheet" type="text/css" href="../_static/profiling-sampling-visualization.css?v=0c2600ae" /> <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" /> <script src="../_static/documentation_options.js?v=6b7c9ff5"></script> <script src="../_static/doctools.js?v=9bcbadda"></script> <script src="../_static/sphinx_highlight.js?v=dc90522c"></script> <script src="../_static/profiling-sampling-visualization.js?v=9811ed04"></script> <script src="../_static/sidebar.js"></script> <link rel="search" type="application/opensearchdescription+xml" title="Search within Python 3.15.0a6 documentation" href="../_static/opensearch.xml"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="copyright" title="Copyright" href="../copyright.html" /> <link rel="next" title="asynchat — Asynchronous socket command/response handler" href="asynchat.html" /> <link rel="prev" title="Removed Modules" href="removed.html" /> <script defer file-types="bz2,epub,zip" data-domain="docs.python.org" src="https://analytics.python.org/js/script.file-downloads.outbound-links.js"></script> <link rel="canonical" href="https://docs.python.org/3/library/aifc.html">
<style> @media only screen { table.full-width-table { width: 100%; } } </style><link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css"> <link rel="shortcut icon" type="image/png" href="../_static/py.svg"> <script type="text/javascript" src="../_static/copybutton.js"></script> <script type="text/javascript" src="../_static/menu.js"></script> <script type="text/javascript" src="../_static/search-focus.js"></script> <script type="text/javascript" src="../_static/themetoggle.js"></script> <script type="text/javascript" src="../_static/rtd_switcher.js"></script> <meta name="readthedocs-addons-api-version" content="1">
</head><body><div class="mobile-nav"> <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation" aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu"> <nav class="nav-content" role="navigation"> <label for="menuToggler" class="toggler__label"> <span></span> </label> <span class="nav-items-wrapper"> <a href="https://www.python.org/" class="nav-logo"> <img src="../_static/py.svg" alt="Python logo"> </a> <span class="version_switcher_placeholder"></span> <form role="search" class="search" action="../search.html" method="get"> <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon"> <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> </svg> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q"> <input type="submit" value="Go"> </form> </span> </nav> <div class="menu-wrapper"> <nav class="menu" role="navigation" aria-label="main navigation"> <div class="language_switcher_placeholder"></div> <label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> <div> <h4>Previous topic</h4> <p class="topless"><a href="removed.html" title="previous chapter">Removed Modules</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="asynchat.html" title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">asynchat</span></code> — Asynchronous socket command/response handler</a></p> </div> <script> document.addEventListener('DOMContentLoaded', () => { const title = document.querySelector('meta[property="og:title"]').content; const elements = document.querySelectorAll('.improvepage'); const pageurl = window.location.href.split('?')[0]; elements.forEach(element => { const url = new URL(element.href.split('?')[0].replace("-nojs", "")); url.searchParams.set('pagetitle', title); url.searchParams.set('pageurl', pageurl); url.searchParams.set('pagesource', "library/aifc.rst"); element.href = url.toString(); }); }); </script> <div role="note" aria-label="source link"> <h3>This page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a bug</a></li> <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li> <li> <a href="https://github.com/python/cpython/blob/main/Doc/library/aifc.rst?plain=1" rel="nofollow">Show source </a> </li> </ul> </div> </nav> </div></div>
<div class="related" role="navigation" aria-label="Related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="asynchat.html" title="asynchat — Asynchronous socket command/response handler" accesskey="N">next</a> |</li> <li class="right" > <a href="removed.html" title="Removed Modules" accesskey="P">previous</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.15.0a6 Documentation</a> » </li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="removed.html" accesskey="U">Removed Modules</a> »</li> <li class="nav-item nav-item-this"><a href=""><code class="xref py py-mod docutils literal notranslate"><span class="pre">aifc</span></code> — Read and write AIFF and AIFC files</a></li> <li class="right">
<div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box"> <input type="submit" value="Go"> </form> </div> | </li> <li class="right"><label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> |</li> </ul> </div>
<div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <section id="module-aifc"><span id="aifc-read-and-write-aiff-and-aifc-files"></span><h1><code class="xref py py-mod docutils literal notranslate"><span class="pre">aifc</span></code> — Read and write AIFF and AIFC files<a class="headerlink" href="#module-aifc" title="Link to this heading">¶</a></h1><div class="deprecated-removed"><p><span class="versionmodified removed">Deprecated since version 3.11, removed in version 3.13.</span></p></div><p>This module is no longer part of the Python standard library.It was <a class="reference internal" href="../whatsnew/3.13.html#whatsnew313-pep594"><span class="std std-ref">removed in Python 3.13</span></a> afterbeing deprecated in Python 3.11. The removal was decided in <span class="target" id="index-0"></span><a class="pep reference external" href="https://peps.python.org/pep-0594/"><strong>PEP 594</strong></a>.</p><p>The last version of Python that provided the <code class="xref py py-mod docutils literal notranslate"><span class="pre">aifc</span></code> module was<a class="reference external" href="https://docs.python.org/3.12/library/aifc.html">Python 3.12</a>.</p></section>
<div class="clearer"></div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="Main"> <div class="sphinxsidebarwrapper"> <div> <h4>Previous topic</h4> <p class="topless"><a href="removed.html" title="previous chapter">Removed Modules</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="asynchat.html" title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">asynchat</span></code> — Asynchronous socket command/response handler</a></p> </div> <script> document.addEventListener('DOMContentLoaded', () => { const title = document.querySelector('meta[property="og:title"]').content; const elements = document.querySelectorAll('.improvepage'); const pageurl = window.location.href.split('?')[0]; elements.forEach(element => { const url = new URL(element.href.split('?')[0].replace("-nojs", "")); url.searchParams.set('pagetitle', title); url.searchParams.set('pageurl', pageurl); url.searchParams.set('pagesource', "library/aifc.rst"); element.href = url.toString(); }); }); </script> <div role="note" aria-label="source link"> <h3>This page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a bug</a></li> <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li> <li> <a href="https://github.com/python/cpython/blob/main/Doc/library/aifc.rst?plain=1" rel="nofollow">Show source </a> </li> </ul> </div> </div><div id="sidebarbutton" title="Collapse sidebar"><span>«</span></div>
</div> <div class="clearer"></div> </div> <div class="related" role="navigation" aria-label="Related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="asynchat.html" title="asynchat — Asynchronous socket command/response handler" >next</a> |</li> <li class="right" > <a href="removed.html" title="Removed Modules" >previous</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.15.0a6 Documentation</a> » </li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="removed.html" >Removed Modules</a> »</li> <li class="nav-item nav-item-this"><a href=""><code class="xref py py-mod docutils literal notranslate"><span class="pre">aifc</span></code> — Read and write AIFF and AIFC files</a></li> <li class="right">
<div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box"> <input type="submit" value="Go"> </form> </div> | </li> <li class="right"><label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> |</li> </ul> </div> <div class="footer"> © <a href="../copyright.html">Copyright</a> 2001 Python Software Foundation. <br> This page is licensed under the Python Software Foundation License Version 2. <br> Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. <br> See <a href="/license.html">History and License</a> for more information.<br> <br>
The Python Software Foundation is a non-profit corporation.<a href="https://www.python.org/psf/donations/">Please donate.</a><br> <br> Last updated on Mar 10, 2026 (08:58 UTC). <a href="/bugs.html">Found a bug</a>? <br>
Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3. </div>
</body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513<!DOCTYPE html>
<html lang="en" data-content_root="../"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta property="og:title" content="Generic Operating System Services" /><meta property="og:type" content="website" /><meta property="og:url" content="https://docs.python.org/3/library/allos.html" /><meta property="og:site_name" content="Python documentation" /><meta property="og:description" content="The modules described in this chapter provide interfaces to operating system features that are available on (almost) all operating systems, such as files and a clock. The interfaces are generally m..." /><meta property="og:image:width" content="1146" /><meta property="og:image:height" content="600" /><meta property="og:image" content="https://docs.python.org/3.15/_images/social_previews/summary_library_allos_86fab500.png" /><meta property="og:image:alt" content="The modules described in this chapter provide interfaces to operating system features that are available on (almost) all operating systems, such as files and a clock. The interfaces are generally m..." /><meta name="description" content="The modules described in this chapter provide interfaces to operating system features that are available on (almost) all operating systems, such as files and a clock. The interfaces are generally m..." /><meta name="twitter:card" content="summary_large_image" /><meta name="theme-color" content="#3776ab">
<title>Generic Operating System Services — Python 3.15.0a6 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" /> <link rel="stylesheet" type="text/css" href="../_static/classic.css?v=234b1a7c" /> <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=89a2f22a" /> <link rel="stylesheet" type="text/css" href="../_static/profiling-sampling-visualization.css?v=0c2600ae" /> <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" /> <script src="../_static/documentation_options.js?v=6b7c9ff5"></script> <script src="../_static/doctools.js?v=9bcbadda"></script> <script src="../_static/sphinx_highlight.js?v=dc90522c"></script> <script src="../_static/profiling-sampling-visualization.js?v=9811ed04"></script> <script src="../_static/sidebar.js"></script> <link rel="search" type="application/opensearchdescription+xml" title="Search within Python 3.15.0a6 documentation" href="../_static/opensearch.xml"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="copyright" title="Copyright" href="../copyright.html" /> <link rel="next" title="os — Miscellaneous operating system interfaces" href="os.html" /> <link rel="prev" title="secrets — Generate secure random numbers for managing secrets" href="secrets.html" /> <script defer file-types="bz2,epub,zip" data-domain="docs.python.org" src="https://analytics.python.org/js/script.file-downloads.outbound-links.js"></script> <link rel="canonical" href="https://docs.python.org/3/library/allos.html">
<style> @media only screen { table.full-width-table { width: 100%; } } </style><link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css"> <link rel="shortcut icon" type="image/png" href="../_static/py.svg"> <script type="text/javascript" src="../_static/copybutton.js"></script> <script type="text/javascript" src="../_static/menu.js"></script> <script type="text/javascript" src="../_static/search-focus.js"></script> <script type="text/javascript" src="../_static/themetoggle.js"></script> <script type="text/javascript" src="../_static/rtd_switcher.js"></script> <meta name="readthedocs-addons-api-version" content="1">
</head><body><div class="mobile-nav"> <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation" aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu"> <nav class="nav-content" role="navigation"> <label for="menuToggler" class="toggler__label"> <span></span> </label> <span class="nav-items-wrapper"> <a href="https://www.python.org/" class="nav-logo"> <img src="../_static/py.svg" alt="Python logo"> </a> <span class="version_switcher_placeholder"></span> <form role="search" class="search" action="../search.html" method="get"> <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon"> <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> </svg> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q"> <input type="submit" value="Go"> </form> </span> </nav> <div class="menu-wrapper"> <nav class="menu" role="navigation" aria-label="main navigation"> <div class="language_switcher_placeholder"></div> <label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> <div> <h4>Previous topic</h4> <p class="topless"><a href="secrets.html" title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">secrets</span></code> — Generate secure random numbers for managing secrets</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="os.html" title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">os</span></code> — Miscellaneous operating system interfaces</a></p> </div> <script> document.addEventListener('DOMContentLoaded', () => { const title = document.querySelector('meta[property="og:title"]').content; const elements = document.querySelectorAll('.improvepage'); const pageurl = window.location.href.split('?')[0]; elements.forEach(element => { const url = new URL(element.href.split('?')[0].replace("-nojs", "")); url.searchParams.set('pagetitle', title); url.searchParams.set('pageurl', pageurl); url.searchParams.set('pagesource', "library/allos.rst"); element.href = url.toString(); }); }); </script> <div role="note" aria-label="source link"> <h3>This page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a bug</a></li> <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li> <li> <a href="https://github.com/python/cpython/blob/main/Doc/library/allos.rst?plain=1" rel="nofollow">Show source </a> </li> </ul> </div> </nav> </div></div>
<div class="related" role="navigation" aria-label="Related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="os.html" title="os — Miscellaneous operating system interfaces" accesskey="N">next</a> |</li> <li class="right" > <a href="secrets.html" title="secrets — Generate secure random numbers for managing secrets" accesskey="P">previous</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.15.0a6 Documentation</a> » </li>
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Standard Library</a> »</li> <li class="nav-item nav-item-this"><a href="">Generic Operating System Services</a></li> <li class="right">
<div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box"> <input type="submit" value="Go"> </form> </div> | </li> <li class="right"><label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> |</li> </ul> </div>
<div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <section id="generic-operating-system-services"><span id="allos"></span><h1>Generic Operating System Services<a class="headerlink" href="#generic-operating-system-services" title="Link to this heading">¶</a></h1><p>The modules described in this chapter provide interfaces to operating systemfeatures that are available on (almost) all operating systems, such as files anda clock. The interfaces are generally modeled after the Unix or C interfaces,but they are available on most other systems as well. Here’s an overview:</p><div class="toctree-wrapper compound"><ul><li class="toctree-l1"><a class="reference internal" href="os.html"><code class="xref py py-mod docutils literal notranslate"><span class="pre">os</span></code> — Miscellaneous operating system interfaces</a><ul><li class="toctree-l2"><a class="reference internal" href="os.html#file-names-command-line-arguments-and-environment-variables">File Names, Command Line Arguments, and Environment Variables</a></li><li class="toctree-l2"><a class="reference internal" href="os.html#python-utf-8-mode">Python UTF-8 Mode</a></li><li class="toctree-l2"><a class="reference internal" href="os.html#process-parameters">Process Parameters</a></li><li class="toctree-l2"><a class="reference internal" href="os.html#file-object-creation">File Object Creation</a></li><li class="toctree-l2"><a class="reference internal" href="os.html#file-descriptor-operations">File Descriptor Operations</a><ul><li class="toctree-l3"><a class="reference internal" href="os.html#querying-the-size-of-a-terminal">Querying the size of a terminal</a></li><li class="toctree-l3"><a class="reference internal" href="os.html#inheritance-of-file-descriptors">Inheritance of File Descriptors</a></li></ul></li><li class="toctree-l2"><a class="reference internal" href="os.html#files-and-directories">Files and Directories</a><ul><li class="toctree-l3"><a class="reference internal" href="os.html#timer-file-descriptors">Timer File Descriptors</a></li><li class="toctree-l3"><a class="reference internal" href="os.html#linux-extended-attributes">Linux extended attributes</a></li></ul></li><li class="toctree-l2"><a class="reference internal" href="os.html#process-management">Process Management</a></li><li class="toctree-l2"><a class="reference internal" href="os.html#interface-to-the-scheduler">Interface to the scheduler</a></li><li class="toctree-l2"><a class="reference internal" href="os.html#miscellaneous-system-information">Miscellaneous System Information</a></li><li class="toctree-l2"><a class="reference internal" href="os.html#random-numbers">Random numbers</a></li></ul></li><li class="toctree-l1"><a class="reference internal" href="io.html"><code class="xref py py-mod docutils literal notranslate"><span class="pre">io</span></code> — Core tools for working with streams</a><ul><li class="toctree-l2"><a class="reference internal" href="io.html#overview">Overview</a><ul><li class="toctree-l3"><a class="reference internal" href="io.html#text-i-o">Text I/O</a></li><li class="toctree-l3"><a class="reference internal" href="io.html#binary-i-o">Binary I/O</a></li><li class="toctree-l3"><a class="reference internal" href="io.html#raw-i-o">Raw I/O</a></li></ul></li><li class="toctree-l2"><a class="reference internal" href="io.html#text-encoding">Text Encoding</a><ul><li class="toctree-l3"><a class="reference internal" href="io.html#opt-in-encodingwarning">Opt-in EncodingWarning</a></li></ul></li><li class="toctree-l2"><a class="reference internal" href="io.html#high-level-module-interface">High-level Module Interface</a></li><li class="toctree-l2"><a class="reference internal" href="io.html#class-hierarchy">Class hierarchy</a><ul><li class="toctree-l3"><a class="reference internal" href="io.html#i-o-base-classes">I/O Base Classes</a></li><li class="toctree-l3"><a class="reference internal" href="io.html#raw-file-i-o">Raw File I/O</a></li><li class="toctree-l3"><a class="reference internal" href="io.html#buffered-streams">Buffered Streams</a></li><li class="toctree-l3"><a class="reference internal" href="io.html#id1">Text I/O</a></li></ul></li><li class="toctree-l2"><a class="reference internal" href="io.html#static-typing">Static Typing</a></li><li class="toctree-l2"><a class="reference internal" href="io.html#performance">Performance</a><ul><li class="toctree-l3"><a class="reference internal" href="io.html#id2">Binary I/O</a></li><li class="toctree-l3"><a class="reference internal" href="io.html#id3">Text I/O</a></li><li class="toctree-l3"><a class="reference internal" href="io.html#multi-threading">Multi-threading</a></li><li class="toctree-l3"><a class="reference internal" href="io.html#reentrancy">Reentrancy</a></li></ul></li></ul></li><li class="toctree-l1"><a class="reference internal" href="time.html"><code class="xref py py-mod docutils literal notranslate"><span class="pre">time</span></code> — Time access and conversions</a><ul><li class="toctree-l2"><a class="reference internal" href="time.html#functions">Functions</a></li><li class="toctree-l2"><a class="reference internal" href="time.html#clock-id-constants">Clock ID Constants</a></li><li class="toctree-l2"><a class="reference internal" href="time.html#timezone-constants">Timezone Constants</a></li></ul></li><li class="toctree-l1"><a class="reference internal" href="logging.html"><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging</span></code> — Logging facility for Python</a><ul><li class="toctree-l2"><a class="reference internal" href="logging.html#logger-objects">Logger Objects</a></li><li class="toctree-l2"><a class="reference internal" href="logging.html#logging-levels">Logging Levels</a></li><li class="toctree-l2"><a class="reference internal" href="logging.html#handler-objects">Handler Objects</a></li><li class="toctree-l2"><a class="reference internal" href="logging.html#formatter-objects">Formatter Objects</a></li><li class="toctree-l2"><a class="reference internal" href="logging.html#filter-objects">Filter Objects</a></li><li class="toctree-l2"><a class="reference internal" href="logging.html#logrecord-objects">LogRecord Objects</a></li><li class="toctree-l2"><a class="reference internal" href="logging.html#logrecord-attributes">LogRecord attributes</a></li><li class="toctree-l2"><a class="reference internal" href="logging.html#loggeradapter-objects">LoggerAdapter Objects</a></li><li class="toctree-l2"><a class="reference internal" href="logging.html#thread-safety">Thread Safety</a></li><li class="toctree-l2"><a class="reference internal" href="logging.html#module-level-functions">Module-Level Functions</a></li><li class="toctree-l2"><a class="reference internal" href="logging.html#module-level-attributes">Module-Level Attributes</a></li><li class="toctree-l2"><a class="reference internal" href="logging.html#integration-with-the-warnings-module">Integration with the warnings module</a></li></ul></li><li class="toctree-l1"><a class="reference internal" href="logging.config.html"><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging.config</span></code> — Logging configuration</a><ul><li class="toctree-l2"><a class="reference internal" href="logging.config.html#configuration-functions">Configuration functions</a></li><li class="toctree-l2"><a class="reference internal" href="logging.config.html#security-considerations">Security considerations</a></li><li class="toctree-l2"><a class="reference internal" href="logging.config.html#configuration-dictionary-schema">Configuration dictionary schema</a><ul><li class="toctree-l3"><a class="reference internal" href="logging.config.html#dictionary-schema-details">Dictionary Schema Details</a></li><li class="toctree-l3"><a class="reference internal" href="logging.config.html#incremental-configuration">Incremental Configuration</a></li><li class="toctree-l3"><a class="reference internal" href="logging.config.html#object-connections">Object connections</a></li><li class="toctree-l3"><a class="reference internal" href="logging.config.html#user-defined-objects">User-defined objects</a></li><li class="toctree-l3"><a class="reference internal" href="logging.config.html#handler-configuration-order">Handler configuration order</a></li><li class="toctree-l3"><a class="reference internal" href="logging.config.html#access-to-external-objects">Access to external objects</a></li><li class="toctree-l3"><a class="reference internal" href="logging.config.html#access-to-internal-objects">Access to internal objects</a></li><li class="toctree-l3"><a class="reference internal" href="logging.config.html#import-resolution-and-custom-importers">Import resolution and custom importers</a></li><li class="toctree-l3"><a class="reference internal" href="logging.config.html#configuring-queuehandler-and-queuelistener">Configuring QueueHandler and QueueListener</a></li></ul></li><li class="toctree-l2"><a class="reference internal" href="logging.config.html#configuration-file-format">Configuration file format</a></li></ul></li><li class="toctree-l1"><a class="reference internal" href="logging.handlers.html"><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging.handlers</span></code> — Logging handlers</a><ul><li class="toctree-l2"><a class="reference internal" href="logging.handlers.html#streamhandler">StreamHandler</a></li><li class="toctree-l2"><a class="reference internal" href="logging.handlers.html#filehandler">FileHandler</a></li><li class="toctree-l2"><a class="reference internal" href="logging.handlers.html#nullhandler">NullHandler</a></li><li class="toctree-l2"><a class="reference internal" href="logging.handlers.html#watchedfilehandler">WatchedFileHandler</a></li><li class="toctree-l2"><a class="reference internal" href="logging.handlers.html#baserotatinghandler">BaseRotatingHandler</a></li><li class="toctree-l2"><a class="reference internal" href="logging.handlers.html#rotatingfilehandler">RotatingFileHandler</a></li><li class="toctree-l2"><a class="reference internal" href="logging.handlers.html#timedrotatingfilehandler">TimedRotatingFileHandler</a></li><li class="toctree-l2"><a class="reference internal" href="logging.handlers.html#sockethandler">SocketHandler</a></li><li class="toctree-l2"><a class="reference internal" href="logging.handlers.html#datagramhandler">DatagramHandler</a></li><li class="toctree-l2"><a class="reference internal" href="logging.handlers.html#sysloghandler">SysLogHandler</a></li><li class="toctree-l2"><a class="reference internal" href="logging.handlers.html#nteventloghandler">NTEventLogHandler</a></li><li class="toctree-l2"><a class="reference internal" href="logging.handlers.html#smtphandler">SMTPHandler</a></li><li class="toctree-l2"><a class="reference internal" href="logging.handlers.html#memoryhandler">MemoryHandler</a></li><li class="toctree-l2"><a class="reference internal" href="logging.handlers.html#httphandler">HTTPHandler</a></li><li class="toctree-l2"><a class="reference internal" href="logging.handlers.html#queuehandler">QueueHandler</a></li><li class="toctree-l2"><a class="reference internal" href="logging.handlers.html#queuelistener">QueueListener</a></li></ul></li><li class="toctree-l1"><a class="reference internal" href="platform.html"><code class="xref py py-mod docutils literal notranslate"><span class="pre">platform</span></code> — Access to underlying platform’s identifying data</a><ul><li class="toctree-l2"><a class="reference internal" href="platform.html#cross-platform">Cross platform</a></li><li class="toctree-l2"><a class="reference internal" href="platform.html#windows-platform">Windows platform</a></li><li class="toctree-l2"><a class="reference internal" href="platform.html#macos-platform">macOS platform</a></li><li class="toctree-l2"><a class="reference internal" href="platform.html#ios-platform">iOS platform</a></li><li class="toctree-l2"><a class="reference internal" href="platform.html#unix-platforms">Unix platforms</a></li><li class="toctree-l2"><a class="reference internal" href="platform.html#linux-platforms">Linux platforms</a></li><li class="toctree-l2"><a class="reference internal" href="platform.html#android-platform">Android platform</a></li><li class="toctree-l2"><a class="reference internal" href="platform.html#command-line-usage">Command-line usage</a></li></ul></li><li class="toctree-l1"><a class="reference internal" href="errno.html"><code class="xref py py-mod docutils literal notranslate"><span class="pre">errno</span></code> — Standard errno system symbols</a></li><li class="toctree-l1"><a class="reference internal" href="ctypes.html"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code> — A foreign function library for Python</a><ul><li class="toctree-l2"><a class="reference internal" href="ctypes.html#ctypes-tutorial">ctypes tutorial</a><ul><li class="toctree-l3"><a class="reference internal" href="ctypes.html#loading-dynamic-link-libraries">Loading dynamic link libraries</a></li><li class="toctree-l3"><a class="reference internal" href="ctypes.html#accessing-functions-from-loaded-dlls">Accessing functions from loaded dlls</a></li><li class="toctree-l3"><a class="reference internal" href="ctypes.html#calling-functions">Calling functions</a></li><li class="toctree-l3"><a class="reference internal" href="ctypes.html#fundamental-data-types">Fundamental data types</a></li><li class="toctree-l3"><a class="reference internal" href="ctypes.html#calling-functions-continued">Calling functions, continued</a></li><li class="toctree-l3"><a class="reference internal" href="ctypes.html#calling-variadic-functions">Calling variadic functions</a></li><li class="toctree-l3"><a class="reference internal" href="ctypes.html#calling-functions-with-your-own-custom-data-types">Calling functions with your own custom data types</a></li><li class="toctree-l3"><a class="reference internal" href="ctypes.html#specifying-the-required-argument-types-function-prototypes">Specifying the required argument types (function prototypes)</a></li><li class="toctree-l3"><a class="reference internal" href="ctypes.html#return-types">Return types</a></li><li class="toctree-l3"><a class="reference internal" href="ctypes.html#passing-pointers-or-passing-parameters-by-reference">Passing pointers (or: passing parameters by reference)</a></li><li class="toctree-l3"><a class="reference internal" href="ctypes.html#structures-and-unions">Structures and unions</a></li><li class="toctree-l3"><a class="reference internal" href="ctypes.html#structure-union-layout-alignment-and-byte-order">Structure/union layout, alignment and byte order</a></li><li class="toctree-l3"><a class="reference internal" href="ctypes.html#bit-fields-in-structures-and-unions">Bit fields in structures and unions</a></li><li class="toctree-l3"><a class="reference internal" href="ctypes.html#arrays">Arrays</a></li><li class="toctree-l3"><a class="reference internal" href="ctypes.html#pointers">Pointers</a></li><li class="toctree-l3"><a class="reference internal" href="ctypes.html#thread-safety-without-the-gil">Thread safety without the GIL</a></li><li class="toctree-l3"><a class="reference internal" href="ctypes.html#type-conversions">Type conversions</a></li><li class="toctree-l3"><a class="reference internal" href="ctypes.html#incomplete-types">Incomplete Types</a></li><li class="toctree-l3"><a class="reference internal" href="ctypes.html#callback-functions">Callback functions</a></li><li class="toctree-l3"><a class="reference internal" href="ctypes.html#accessing-values-exported-from-dlls">Accessing values exported from dlls</a></li><li class="toctree-l3"><a class="reference internal" href="ctypes.html#surprises">Surprises</a></li><li class="toctree-l3"><a class="reference internal" href="ctypes.html#variable-sized-data-types">Variable-sized data types</a></li></ul></li><li class="toctree-l2"><a class="reference internal" href="ctypes.html#ctypes-reference">ctypes reference</a><ul><li class="toctree-l3"><a class="reference internal" href="ctypes.html#finding-shared-libraries">Finding shared libraries</a></li><li class="toctree-l3"><a class="reference internal" href="ctypes.html#listing-loaded-shared-libraries">Listing loaded shared libraries</a></li><li class="toctree-l3"><a class="reference internal" href="ctypes.html#loading-shared-libraries">Loading shared libraries</a></li><li class="toctree-l3"><a class="reference internal" href="ctypes.html#foreign-functions">Foreign functions</a></li><li class="toctree-l3"><a class="reference internal" href="ctypes.html#function-prototypes">Function prototypes</a></li><li class="toctree-l3"><a class="reference internal" href="ctypes.html#utility-functions">Utility functions</a></li><li class="toctree-l3"><a class="reference internal" href="ctypes.html#data-types">Data types</a></li><li class="toctree-l3"><a class="reference internal" href="ctypes.html#ctypes-fundamental-data-types-2">Fundamental data types</a></li><li class="toctree-l3"><a class="reference internal" href="ctypes.html#structured-data-types">Structured data types</a></li><li class="toctree-l3"><a class="reference internal" href="ctypes.html#arrays-and-pointers">Arrays and pointers</a></li><li class="toctree-l3"><a class="reference internal" href="ctypes.html#exceptions">Exceptions</a></li></ul></li></ul></li></ul></div></section>
<div class="clearer"></div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="Main"> <div class="sphinxsidebarwrapper"> <div> <h4>Previous topic</h4> <p class="topless"><a href="secrets.html" title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">secrets</span></code> — Generate secure random numbers for managing secrets</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="os.html" title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">os</span></code> — Miscellaneous operating system interfaces</a></p> </div> <script> document.addEventListener('DOMContentLoaded', () => { const title = document.querySelector('meta[property="og:title"]').content; const elements = document.querySelectorAll('.improvepage'); const pageurl = window.location.href.split('?')[0]; elements.forEach(element => { const url = new URL(element.href.split('?')[0].replace("-nojs", "")); url.searchParams.set('pagetitle', title); url.searchParams.set('pageurl', pageurl); url.searchParams.set('pagesource', "library/allos.rst"); element.href = url.toString(); }); }); </script> <div role="note" aria-label="source link"> <h3>This page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a bug</a></li> <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li> <li> <a href="https://github.com/python/cpython/blob/main/Doc/library/allos.rst?plain=1" rel="nofollow">Show source </a> </li> </ul> </div> </div><div id="sidebarbutton" title="Collapse sidebar"><span>«</span></div>
</div> <div class="clearer"></div> </div> <div class="related" role="navigation" aria-label="Related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="os.html" title="os — Miscellaneous operating system interfaces" >next</a> |</li> <li class="right" > <a href="secrets.html" title="secrets — Generate secure random numbers for managing secrets" >previous</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.15.0a6 Documentation</a> » </li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-this"><a href="">Generic Operating System Services</a></li> <li class="right">
<div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box"> <input type="submit" value="Go"> </form> </div> | </li> <li class="right"><label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> |</li> </ul> </div> <div class="footer"> © <a href="../copyright.html">Copyright</a> 2001 Python Software Foundation. <br> This page is licensed under the Python Software Foundation License Version 2. <br> Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. <br> See <a href="/license.html">History and License</a> for more information.<br> <br>
The Python Software Foundation is a non-profit corporation.<a href="https://www.python.org/psf/donations/">Please donate.</a><br> <br> Last updated on Mar 10, 2026 (08:58 UTC). <a href="/bugs.html">Found a bug</a>? <br>
Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3. </div>
</body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429<!DOCTYPE html>
<html lang="en" data-content_root="../"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta property="og:title" content="Data Compression and Archiving" /><meta property="og:type" content="website" /><meta property="og:url" content="https://docs.python.org/3/library/archiving.html" /><meta property="og:site_name" content="Python documentation" /><meta property="og:description" content="The modules described in this chapter support data compression with the zlib, gzip, bzip2, lzma, and zstd algorithms, and the creation of ZIP- and tar-format archives. See also Archiving operations..." /><meta property="og:image:width" content="1146" /><meta property="og:image:height" content="600" /><meta property="og:image" content="https://docs.python.org/3.15/_images/social_previews/summary_library_archiving_c72287bb.png" /><meta property="og:image:alt" content="The modules described in this chapter support data compression with the zlib, gzip, bzip2, lzma, and zstd algorithms, and the creation of ZIP- and tar-format archives. See also Archiving operations..." /><meta name="description" content="The modules described in this chapter support data compression with the zlib, gzip, bzip2, lzma, and zstd algorithms, and the creation of ZIP- and tar-format archives. See also Archiving operations..." /><meta name="twitter:card" content="summary_large_image" /><meta name="theme-color" content="#3776ab">
<title>Data Compression and Archiving — Python 3.15.0a6 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" /> <link rel="stylesheet" type="text/css" href="../_static/classic.css?v=234b1a7c" /> <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=89a2f22a" /> <link rel="stylesheet" type="text/css" href="../_static/profiling-sampling-visualization.css?v=0c2600ae" /> <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" /> <script src="../_static/documentation_options.js?v=6b7c9ff5"></script> <script src="../_static/doctools.js?v=9bcbadda"></script> <script src="../_static/sphinx_highlight.js?v=dc90522c"></script> <script src="../_static/profiling-sampling-visualization.js?v=9811ed04"></script> <script src="../_static/sidebar.js"></script> <link rel="search" type="application/opensearchdescription+xml" title="Search within Python 3.15.0a6 documentation" href="../_static/opensearch.xml"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="copyright" title="Copyright" href="../copyright.html" /> <link rel="next" title="The compression package" href="compression.html" /> <link rel="prev" title="sqlite3 — DB-API 2.0 interface for SQLite databases" href="sqlite3.html" /> <script defer file-types="bz2,epub,zip" data-domain="docs.python.org" src="https://analytics.python.org/js/script.file-downloads.outbound-links.js"></script> <link rel="canonical" href="https://docs.python.org/3/library/archiving.html">
<style> @media only screen { table.full-width-table { width: 100%; } } </style><link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css"> <link rel="shortcut icon" type="image/png" href="../_static/py.svg"> <script type="text/javascript" src="../_static/copybutton.js"></script> <script type="text/javascript" src="../_static/menu.js"></script> <script type="text/javascript" src="../_static/search-focus.js"></script> <script type="text/javascript" src="../_static/themetoggle.js"></script> <script type="text/javascript" src="../_static/rtd_switcher.js"></script> <meta name="readthedocs-addons-api-version" content="1">
</head><body><div class="mobile-nav"> <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation" aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu"> <nav class="nav-content" role="navigation"> <label for="menuToggler" class="toggler__label"> <span></span> </label> <span class="nav-items-wrapper"> <a href="https://www.python.org/" class="nav-logo"> <img src="../_static/py.svg" alt="Python logo"> </a> <span class="version_switcher_placeholder"></span> <form role="search" class="search" action="../search.html" method="get"> <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon"> <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> </svg> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q"> <input type="submit" value="Go"> </form> </span> </nav> <div class="menu-wrapper"> <nav class="menu" role="navigation" aria-label="main navigation"> <div class="language_switcher_placeholder"></div> <label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> <div> <h4>Previous topic</h4> <p class="topless"><a href="sqlite3.html" title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">sqlite3</span></code> — DB-API 2.0 interface for SQLite databases</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="compression.html" title="next chapter">The <code class="xref py py-mod docutils literal notranslate"><span class="pre">compression</span></code> package</a></p> </div> <script> document.addEventListener('DOMContentLoaded', () => { const title = document.querySelector('meta[property="og:title"]').content; const elements = document.querySelectorAll('.improvepage'); const pageurl = window.location.href.split('?')[0]; elements.forEach(element => { const url = new URL(element.href.split('?')[0].replace("-nojs", "")); url.searchParams.set('pagetitle', title); url.searchParams.set('pageurl', pageurl); url.searchParams.set('pagesource', "library/archiving.rst"); element.href = url.toString(); }); }); </script> <div role="note" aria-label="source link"> <h3>This page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a bug</a></li> <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li> <li> <a href="https://github.com/python/cpython/blob/main/Doc/library/archiving.rst?plain=1" rel="nofollow">Show source </a> </li> </ul> </div> </nav> </div></div>
<div class="related" role="navigation" aria-label="Related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="compression.html" title="The compression package" accesskey="N">next</a> |</li> <li class="right" > <a href="sqlite3.html" title="sqlite3 — DB-API 2.0 interface for SQLite databases" accesskey="P">previous</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.15.0a6 Documentation</a> » </li>
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Standard Library</a> »</li> <li class="nav-item nav-item-this"><a href="">Data Compression and Archiving</a></li> <li class="right">
<div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box"> <input type="submit" value="Go"> </form> </div> | </li> <li class="right"><label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> |</li> </ul> </div>
<div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <section id="data-compression-and-archiving"><span id="archiving"></span><h1>Data Compression and Archiving<a class="headerlink" href="#data-compression-and-archiving" title="Link to this heading">¶</a></h1><p>The modules described in this chapter support data compression with the zlib,gzip, bzip2, lzma, and zstd algorithms, and the creation of ZIP- and tar-formatarchives. See also <a class="reference internal" href="shutil.html#archiving-operations"><span class="std std-ref">Archiving operations</span></a> provided by the <a class="reference internal" href="shutil.html#module-shutil" title="shutil: High-level file operations, including copying."><code class="xref py py-mod docutils literal notranslate"><span class="pre">shutil</span></code></a>module.</p><div class="toctree-wrapper compound"><ul><li class="toctree-l1"><a class="reference internal" href="compression.html">The <code class="xref py py-mod docutils literal notranslate"><span class="pre">compression</span></code> package</a></li><li class="toctree-l1"><a class="reference internal" href="compression.zstd.html"><code class="xref py py-mod docutils literal notranslate"><span class="pre">compression.zstd</span></code> — Compression compatible with the Zstandard format</a><ul><li class="toctree-l2"><a class="reference internal" href="compression.zstd.html#exceptions">Exceptions</a></li><li class="toctree-l2"><a class="reference internal" href="compression.zstd.html#reading-and-writing-compressed-files">Reading and writing compressed files</a></li><li class="toctree-l2"><a class="reference internal" href="compression.zstd.html#compressing-and-decompressing-data-in-memory">Compressing and decompressing data in memory</a></li><li class="toctree-l2"><a class="reference internal" href="compression.zstd.html#zstandard-dictionaries">Zstandard dictionaries</a></li><li class="toctree-l2"><a class="reference internal" href="compression.zstd.html#advanced-parameter-control">Advanced parameter control</a></li><li class="toctree-l2"><a class="reference internal" href="compression.zstd.html#miscellaneous">Miscellaneous</a></li><li class="toctree-l2"><a class="reference internal" href="compression.zstd.html#examples">Examples</a></li></ul></li><li class="toctree-l1"><a class="reference internal" href="zlib.html"><code class="xref py py-mod docutils literal notranslate"><span class="pre">zlib</span></code> — Compression compatible with <strong class="program">gzip</strong></a></li><li class="toctree-l1"><a class="reference internal" href="gzip.html"><code class="xref py py-mod docutils literal notranslate"><span class="pre">gzip</span></code> — Support for <strong class="program">gzip</strong> files</a><ul><li class="toctree-l2"><a class="reference internal" href="gzip.html#examples-of-usage">Examples of usage</a></li><li class="toctree-l2"><a class="reference internal" href="gzip.html#command-line-interface">Command-line interface</a><ul><li class="toctree-l3"><a class="reference internal" href="gzip.html#command-line-options">Command-line options</a></li></ul></li></ul></li><li class="toctree-l1"><a class="reference internal" href="bz2.html"><code class="xref py py-mod docutils literal notranslate"><span class="pre">bz2</span></code> — Support for <strong class="program">bzip2</strong> compression</a><ul><li class="toctree-l2"><a class="reference internal" href="bz2.html#de-compression-of-files">(De)compression of files</a></li><li class="toctree-l2"><a class="reference internal" href="bz2.html#incremental-de-compression">Incremental (de)compression</a></li><li class="toctree-l2"><a class="reference internal" href="bz2.html#one-shot-de-compression">One-shot (de)compression</a></li><li class="toctree-l2"><a class="reference internal" href="bz2.html#examples-of-usage">Examples of usage</a></li></ul></li><li class="toctree-l1"><a class="reference internal" href="lzma.html"><code class="xref py py-mod docutils literal notranslate"><span class="pre">lzma</span></code> — Compression using the LZMA algorithm</a><ul><li class="toctree-l2"><a class="reference internal" href="lzma.html#reading-and-writing-compressed-files">Reading and writing compressed files</a></li><li class="toctree-l2"><a class="reference internal" href="lzma.html#compressing-and-decompressing-data-in-memory">Compressing and decompressing data in memory</a></li><li class="toctree-l2"><a class="reference internal" href="lzma.html#miscellaneous">Miscellaneous</a></li><li class="toctree-l2"><a class="reference internal" href="lzma.html#specifying-custom-filter-chains">Specifying custom filter chains</a></li><li class="toctree-l2"><a class="reference internal" href="lzma.html#examples">Examples</a></li></ul></li><li class="toctree-l1"><a class="reference internal" href="zipfile.html"><code class="xref py py-mod docutils literal notranslate"><span class="pre">zipfile</span></code> — Work with ZIP archives</a><ul><li class="toctree-l2"><a class="reference internal" href="zipfile.html#zipfile-objects">ZipFile objects</a></li><li class="toctree-l2"><a class="reference internal" href="zipfile.html#path-objects">Path objects</a></li><li class="toctree-l2"><a class="reference internal" href="zipfile.html#pyzipfile-objects">PyZipFile objects</a></li><li class="toctree-l2"><a class="reference internal" href="zipfile.html#zipinfo-objects">ZipInfo objects</a></li><li class="toctree-l2"><a class="reference internal" href="zipfile.html#command-line-interface">Command-line interface</a><ul><li class="toctree-l3"><a class="reference internal" href="zipfile.html#command-line-options">Command-line options</a></li></ul></li><li class="toctree-l2"><a class="reference internal" href="zipfile.html#decompression-pitfalls">Decompression pitfalls</a><ul><li class="toctree-l3"><a class="reference internal" href="zipfile.html#from-file-itself">From file itself</a></li><li class="toctree-l3"><a class="reference internal" href="zipfile.html#file-system-limitations">File system limitations</a></li><li class="toctree-l3"><a class="reference internal" href="zipfile.html#resources-limitations">Resources limitations</a></li><li class="toctree-l3"><a class="reference internal" href="zipfile.html#interruption">Interruption</a></li><li class="toctree-l3"><a class="reference internal" href="zipfile.html#default-behaviors-of-extraction">Default behaviors of extraction</a></li></ul></li></ul></li><li class="toctree-l1"><a class="reference internal" href="tarfile.html"><code class="xref py py-mod docutils literal notranslate"><span class="pre">tarfile</span></code> — Read and write tar archive files</a><ul><li class="toctree-l2"><a class="reference internal" href="tarfile.html#tarfile-objects">TarFile Objects</a></li><li class="toctree-l2"><a class="reference internal" href="tarfile.html#tarinfo-objects">TarInfo Objects</a></li><li class="toctree-l2"><a class="reference internal" href="tarfile.html#extraction-filters">Extraction filters</a><ul><li class="toctree-l3"><a class="reference internal" href="tarfile.html#default-named-filters">Default named filters</a></li><li class="toctree-l3"><a class="reference internal" href="tarfile.html#filter-errors">Filter errors</a></li><li class="toctree-l3"><a class="reference internal" href="tarfile.html#hints-for-further-verification">Hints for further verification</a></li><li class="toctree-l3"><a class="reference internal" href="tarfile.html#supporting-older-python-versions">Supporting older Python versions</a></li><li class="toctree-l3"><a class="reference internal" href="tarfile.html#stateful-extraction-filter-example">Stateful extraction filter example</a></li></ul></li><li class="toctree-l2"><a class="reference internal" href="tarfile.html#command-line-interface">Command-Line Interface</a><ul><li class="toctree-l3"><a class="reference internal" href="tarfile.html#command-line-options">Command-line options</a></li></ul></li><li class="toctree-l2"><a class="reference internal" href="tarfile.html#examples">Examples</a><ul><li class="toctree-l3"><a class="reference internal" href="tarfile.html#reading-examples">Reading examples</a></li><li class="toctree-l3"><a class="reference internal" href="tarfile.html#writing-examples">Writing examples</a></li></ul></li><li class="toctree-l2"><a class="reference internal" href="tarfile.html#supported-tar-formats">Supported tar formats</a></li><li class="toctree-l2"><a class="reference internal" href="tarfile.html#unicode-issues">Unicode issues</a></li></ul></li></ul></div></section>
<div class="clearer"></div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="Main"> <div class="sphinxsidebarwrapper"> <div> <h4>Previous topic</h4> <p class="topless"><a href="sqlite3.html" title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">sqlite3</span></code> — DB-API 2.0 interface for SQLite databases</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="compression.html" title="next chapter">The <code class="xref py py-mod docutils literal notranslate"><span class="pre">compression</span></code> package</a></p> </div> <script> document.addEventListener('DOMContentLoaded', () => { const title = document.querySelector('meta[property="og:title"]').content; const elements = document.querySelectorAll('.improvepage'); const pageurl = window.location.href.split('?')[0]; elements.forEach(element => { const url = new URL(element.href.split('?')[0].replace("-nojs", "")); url.searchParams.set('pagetitle', title); url.searchParams.set('pageurl', pageurl); url.searchParams.set('pagesource', "library/archiving.rst"); element.href = url.toString(); }); }); </script> <div role="note" aria-label="source link"> <h3>This page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a bug</a></li> <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li> <li> <a href="https://github.com/python/cpython/blob/main/Doc/library/archiving.rst?plain=1" rel="nofollow">Show source </a> </li> </ul> </div> </div><div id="sidebarbutton" title="Collapse sidebar"><span>«</span></div>
</div> <div class="clearer"></div> </div> <div class="related" role="navigation" aria-label="Related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="compression.html" title="The compression package" >next</a> |</li> <li class="right" > <a href="sqlite3.html" title="sqlite3 — DB-API 2.0 interface for SQLite databases" >previous</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.15.0a6 Documentation</a> » </li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-this"><a href="">Data Compression and Archiving</a></li> <li class="right">
<div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box"> <input type="submit" value="Go"> </form> </div> | </li> <li class="right"><label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> |</li> </ul> </div> <div class="footer"> © <a href="../copyright.html">Copyright</a> 2001 Python Software Foundation. <br> This page is licensed under the Python Software Foundation License Version 2. <br> Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. <br> See <a href="/license.html">History and License</a> for more information.<br> <br>
The Python Software Foundation is a non-profit corporation.<a href="https://www.python.org/psf/donations/">Please donate.</a><br> <br> Last updated on Mar 10, 2026 (08:58 UTC). <a href="/bugs.html">Found a bug</a>? <br>
Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3. </div>
</body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700<!DOCTYPE html>
<html lang="en" data-content_root="../"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta property="og:title" content="array — Efficient arrays of numeric values" /><meta property="og:type" content="website" /><meta property="og:url" content="https://docs.python.org/3/library/array.html" /><meta property="og:site_name" content="Python documentation" /><meta property="og:description" content="This module defines an object type which can compactly represent an array of basic values: characters, integers, floating-point numbers. Arrays are mutable sequence types and behave very much like ..." /><meta property="og:image:width" content="1146" /><meta property="og:image:height" content="600" /><meta property="og:image" content="https://docs.python.org/3.15/_images/social_previews/summary_library_array_2228e7ad.png" /><meta property="og:image:alt" content="This module defines an object type which can compactly represent an array of basic values: characters, integers, floating-point numbers. Arrays are mutable sequence types and behave very much like ..." /><meta name="description" content="This module defines an object type which can compactly represent an array of basic values: characters, integers, floating-point numbers. Arrays are mutable sequence types and behave very much like ..." /><meta name="twitter:card" content="summary_large_image" /><meta name="theme-color" content="#3776ab">
<title>array — Efficient arrays of numeric values — Python 3.15.0a6 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" /> <link rel="stylesheet" type="text/css" href="../_static/classic.css?v=234b1a7c" /> <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=89a2f22a" /> <link rel="stylesheet" type="text/css" href="../_static/profiling-sampling-visualization.css?v=0c2600ae" /> <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" /> <script src="../_static/documentation_options.js?v=6b7c9ff5"></script> <script src="../_static/doctools.js?v=9bcbadda"></script> <script src="../_static/sphinx_highlight.js?v=dc90522c"></script> <script src="../_static/profiling-sampling-visualization.js?v=9811ed04"></script> <script src="../_static/sidebar.js"></script> <link rel="search" type="application/opensearchdescription+xml" title="Search within Python 3.15.0a6 documentation" href="../_static/opensearch.xml"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="copyright" title="Copyright" href="../copyright.html" /> <link rel="next" title="weakref — Weak references" href="weakref.html" /> <link rel="prev" title="bisect — Array bisection algorithm" href="bisect.html" /> <script defer file-types="bz2,epub,zip" data-domain="docs.python.org" src="https://analytics.python.org/js/script.file-downloads.outbound-links.js"></script> <link rel="canonical" href="https://docs.python.org/3/library/array.html">
<style> @media only screen { table.full-width-table { width: 100%; } } </style><link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css"> <link rel="shortcut icon" type="image/png" href="../_static/py.svg"> <script type="text/javascript" src="../_static/copybutton.js"></script> <script type="text/javascript" src="../_static/menu.js"></script> <script type="text/javascript" src="../_static/search-focus.js"></script> <script type="text/javascript" src="../_static/themetoggle.js"></script> <script type="text/javascript" src="../_static/rtd_switcher.js"></script> <meta name="readthedocs-addons-api-version" content="1">
</head><body><div class="mobile-nav"> <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation" aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu"> <nav class="nav-content" role="navigation"> <label for="menuToggler" class="toggler__label"> <span></span> </label> <span class="nav-items-wrapper"> <a href="https://www.python.org/" class="nav-logo"> <img src="../_static/py.svg" alt="Python logo"> </a> <span class="version_switcher_placeholder"></span> <form role="search" class="search" action="../search.html" method="get"> <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon"> <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> </svg> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q"> <input type="submit" value="Go"> </form> </span> </nav> <div class="menu-wrapper"> <nav class="menu" role="navigation" aria-label="main navigation"> <div class="language_switcher_placeholder"></div> <label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> <div> <h4>Previous topic</h4> <p class="topless"><a href="bisect.html" title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">bisect</span></code> — Array bisection algorithm</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="weakref.html" title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">weakref</span></code> — Weak references</a></p> </div> <script> document.addEventListener('DOMContentLoaded', () => { const title = document.querySelector('meta[property="og:title"]').content; const elements = document.querySelectorAll('.improvepage'); const pageurl = window.location.href.split('?')[0]; elements.forEach(element => { const url = new URL(element.href.split('?')[0].replace("-nojs", "")); url.searchParams.set('pagetitle', title); url.searchParams.set('pageurl', pageurl); url.searchParams.set('pagesource', "library/array.rst"); element.href = url.toString(); }); }); </script> <div role="note" aria-label="source link"> <h3>This page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a bug</a></li> <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li> <li> <a href="https://github.com/python/cpython/blob/main/Doc/library/array.rst?plain=1" rel="nofollow">Show source </a> </li> </ul> </div> </nav> </div></div>
<div class="related" role="navigation" aria-label="Related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="weakref.html" title="weakref — Weak references" accesskey="N">next</a> |</li> <li class="right" > <a href="bisect.html" title="bisect — Array bisection algorithm" accesskey="P">previous</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.15.0a6 Documentation</a> » </li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="datatypes.html" accesskey="U">Data Types</a> »</li> <li class="nav-item nav-item-this"><a href=""><code class="xref py py-mod docutils literal notranslate"><span class="pre">array</span></code> — Efficient arrays of numeric values</a></li> <li class="right">
<div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box"> <input type="submit" value="Go"> </form> </div> | </li> <li class="right"><label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> |</li> </ul> </div>
<div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <section id="module-array"><span id="array-efficient-arrays-of-numeric-values"></span><h1><code class="xref py py-mod docutils literal notranslate"><span class="pre">array</span></code> — Efficient arrays of numeric values<a class="headerlink" href="#module-array" title="Link to this heading">¶</a></h1><hr class="docutils" id="index-0" /><p>This module defines an object type which can compactly represent an array ofbasic values: characters, integers, floating-point numbers. Arrays are mutable <a class="reference internal" href="../glossary.html#term-sequence"><span class="xref std std-term">sequence</span></a>types and behave very much like lists, except that the type of objects stored inthem is constrained. The type is specified at object creation time by using a<em class="dfn">type code</em>, which is a single character. The following type codes aredefined:</p><table class="docutils align-default"><thead><tr class="row-odd"><th class="head"><p>Type code</p></th><th class="head"><p>C Type</p></th><th class="head"><p>Python Type</p></th><th class="head"><p>Minimum size in bytes</p></th><th class="head"><p>Notes</p></th></tr></thead><tbody><tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">'b'</span></code></p></td><td><p>signed char</p></td><td><p>int</p></td><td><p>1</p></td><td></td></tr><tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">'B'</span></code></p></td><td><p>unsigned char</p></td><td><p>int</p></td><td><p>1</p></td><td></td></tr><tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">'u'</span></code></p></td><td><p>wchar_t</p></td><td><p>Unicode character</p></td><td><p>2</p></td><td><p>(1)</p></td></tr><tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">'w'</span></code></p></td><td><p>Py_UCS4</p></td><td><p>Unicode character</p></td><td><p>4</p></td><td><p>(2)</p></td></tr><tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">'h'</span></code></p></td><td><p>signed short</p></td><td><p>int</p></td><td><p>2</p></td><td></td></tr><tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">'H'</span></code></p></td><td><p>unsigned short</p></td><td><p>int</p></td><td><p>2</p></td><td></td></tr><tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">'i'</span></code></p></td><td><p>signed int</p></td><td><p>int</p></td><td><p>2</p></td><td></td></tr><tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">'I'</span></code></p></td><td><p>unsigned int</p></td><td><p>int</p></td><td><p>2</p></td><td></td></tr><tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">'l'</span></code></p></td><td><p>signed long</p></td><td><p>int</p></td><td><p>4</p></td><td></td></tr><tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">'L'</span></code></p></td><td><p>unsigned long</p></td><td><p>int</p></td><td><p>4</p></td><td></td></tr><tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">'q'</span></code></p></td><td><p>signed long long</p></td><td><p>int</p></td><td><p>8</p></td><td></td></tr><tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">'Q'</span></code></p></td><td><p>unsigned long long</p></td><td><p>int</p></td><td><p>8</p></td><td></td></tr><tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">'f'</span></code></p></td><td><p>float</p></td><td><p>float</p></td><td><p>4</p></td><td></td></tr><tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">'d'</span></code></p></td><td><p>double</p></td><td><p>float</p></td><td><p>8</p></td><td></td></tr></tbody></table><p>Notes:</p><ol class="arabic"><li><p>It can be 16 bits or 32 bits depending on the platform.</p><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.9: </span><code class="docutils literal notranslate"><span class="pre">array('u')</span></code> now uses <code class="xref c c-type docutils literal notranslate"><span class="pre">wchar_t</span></code> as C type instead of deprecated<code class="docutils literal notranslate"><span class="pre">Py_UNICODE</span></code>. This change doesn’t affect its behavior because<code class="docutils literal notranslate"><span class="pre">Py_UNICODE</span></code> is alias of <code class="xref c c-type docutils literal notranslate"><span class="pre">wchar_t</span></code> since Python 3.3.</p></div><div class="deprecated-removed"><p><span class="versionmodified deprecated">Deprecated since version 3.3, will be removed in version 3.16: </span>Please migrate to <code class="docutils literal notranslate"><span class="pre">'w'</span></code> typecode.</p></div></li><li><div class="versionadded"><p><span class="versionmodified added">Added in version 3.13.</span></p></div></li></ol><p>The actual representation of values is determined by the machine architecture(strictly speaking, by the C implementation). The actual size can be accessedthrough the <a class="reference internal" href="#array.array.itemsize" title="array.array.itemsize"><code class="xref py py-attr docutils literal notranslate"><span class="pre">array.itemsize</span></code></a> attribute.</p><p>The module defines the following item:</p><dl class="py data"><dt class="sig sig-object py" id="array.typecodes"><span class="sig-prename descclassname"><span class="pre">array.</span></span><span class="sig-name descname"><span class="pre">typecodes</span></span><a class="headerlink" href="#array.typecodes" title="Link to this definition">¶</a></dt><dd><p>A string with all available type codes.</p></dd></dl>
<p>The module defines the following type:</p><dl class="py class"><dt class="sig sig-object py" id="array.array"><em class="property"><span class="k"><span class="pre">class</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">array.</span></span><span class="sig-name descname"><span class="pre">array</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">typecode</span></span></em><span class="optional">[</span>, <em class="sig-param"><span class="n"><span class="pre">initializer</span></span></em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#array.array" title="Link to this definition">¶</a></dt><dd><p>A new array whose items are restricted by <em>typecode</em>, and initializedfrom the optional <em>initializer</em> value, which must be a <a class="reference internal" href="stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a>or <a class="reference internal" href="stdtypes.html#bytearray" title="bytearray"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytearray</span></code></a> object, a Unicode string, or iterable over elementsof the appropriate type.</p><p>If given a <a class="reference internal" href="stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> or <a class="reference internal" href="stdtypes.html#bytearray" title="bytearray"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytearray</span></code></a> object, the initializeris passed to the new array’s <a class="reference internal" href="#array.array.frombytes" title="array.array.frombytes"><code class="xref py py-meth docutils literal notranslate"><span class="pre">frombytes()</span></code></a> method;if given a Unicode string, the initializer is passed to the<a class="reference internal" href="#array.array.fromunicode" title="array.array.fromunicode"><code class="xref py py-meth docutils literal notranslate"><span class="pre">fromunicode()</span></code></a> method;otherwise, the initializer’s iterator is passed to the <a class="reference internal" href="#array.array.extend" title="array.array.extend"><code class="xref py py-meth docutils literal notranslate"><span class="pre">extend()</span></code></a> methodto add initial items to the array.</p><p>Array objects support the ordinary <a class="reference internal" href="stdtypes.html#typesseq-mutable"><span class="std std-ref">mutable</span></a> <a class="reference internal" href="../glossary.html#term-sequence"><span class="xref std std-term">sequence</span></a> operations of indexing, slicing,concatenation, and multiplication. When using slice assignment, the assignedvalue must be an array object with the same type code; in all other cases,<a class="reference internal" href="exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> is raised. Array objects also implement the buffer interface,and may be used wherever <a class="reference internal" href="../glossary.html#term-bytes-like-object"><span class="xref std std-term">bytes-like objects</span></a> are supported.</p><p class="audit-hook">Raises an <a class="reference internal" href="sys.html#auditing"><span class="std std-ref">auditing event</span></a> <code class="docutils literal notranslate"><span class="pre">array.__new__</span></code> with arguments <code class="docutils literal notranslate"><span class="pre">typecode</span></code>, <code class="docutils literal notranslate"><span class="pre">initializer</span></code>.</p><dl class="py attribute"><dt class="sig sig-object py" id="array.array.typecode"><span class="sig-name descname"><span class="pre">typecode</span></span><a class="headerlink" href="#array.array.typecode" title="Link to this definition">¶</a></dt><dd><p>The typecode character used to create the array.</p></dd></dl>
<dl class="py attribute"><dt class="sig sig-object py" id="array.array.itemsize"><span class="sig-name descname"><span class="pre">itemsize</span></span><a class="headerlink" href="#array.array.itemsize" title="Link to this definition">¶</a></dt><dd><p>The length in bytes of one array item in the internal representation.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="array.array.append"><span class="sig-name descname"><span class="pre">append</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">x</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#array.array.append" title="Link to this definition">¶</a></dt><dd><p>Append a new item with value <em>x</em> to the end of the array.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="array.array.buffer_info"><span class="sig-name descname"><span class="pre">buffer_info</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#array.array.buffer_info" title="Link to this definition">¶</a></dt><dd><p>Return a tuple <code class="docutils literal notranslate"><span class="pre">(address,</span> <span class="pre">length)</span></code> giving the current memory address and thelength in elements of the buffer used to hold array’s contents. The size of thememory buffer in bytes can be computed as <code class="docutils literal notranslate"><span class="pre">array.buffer_info()[1]</span> <span class="pre">*</span><span class="pre">array.itemsize</span></code>. This is occasionally useful when working with low-level (andinherently unsafe) I/O interfaces that require memory addresses, such as certain<code class="xref c c-func docutils literal notranslate"><span class="pre">ioctl()</span></code> operations. The returned numbers are valid as long as the arrayexists and no length-changing operations are applied to it.</p><div class="admonition note"><p class="admonition-title">Note</p><p>When using array objects from code written in C or C++ (the only way toeffectively make use of this information), it makes more sense to use the bufferinterface supported by array objects. This method is maintained for backwardcompatibility and should be avoided in new code. The buffer interface isdocumented in <a class="reference internal" href="../c-api/buffer.html#bufferobjects"><span class="std std-ref">Buffer Protocol</span></a>.</p></div></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="array.array.byteswap"><span class="sig-name descname"><span class="pre">byteswap</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#array.array.byteswap" title="Link to this definition">¶</a></dt><dd><p>“Byteswap” all items of the array. This is only supported for values which are1, 2, 4, or 8 bytes in size; for other types of values, <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> israised. It is useful when reading data from a file written on a machine with adifferent byte order.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="array.array.count"><span class="sig-name descname"><span class="pre">count</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">x</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#array.array.count" title="Link to this definition">¶</a></dt><dd><p>Return the number of occurrences of <em>x</em> in the array.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="array.array.extend"><span class="sig-name descname"><span class="pre">extend</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">iterable</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#array.array.extend" title="Link to this definition">¶</a></dt><dd><p>Append items from <em>iterable</em> to the end of the array. If <em>iterable</em> is anotherarray, it must have <em>exactly</em> the same type code; if not, <a class="reference internal" href="exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> willbe raised. If <em>iterable</em> is not an array, it must be iterable and its elementsmust be the right type to be appended to the array.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="array.array.frombytes"><span class="sig-name descname"><span class="pre">frombytes</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">buffer</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#array.array.frombytes" title="Link to this definition">¶</a></dt><dd><p>Appends items from the <a class="reference internal" href="../glossary.html#term-bytes-like-object"><span class="xref std std-term">bytes-like object</span></a>, interpretingits content as an array of machine values (as if it had been readfrom a file using the <a class="reference internal" href="#array.array.fromfile" title="array.array.fromfile"><code class="xref py py-meth docutils literal notranslate"><span class="pre">fromfile()</span></code></a> method).</p><div class="versionadded"><p><span class="versionmodified added">Added in version 3.2: </span><code class="xref py py-meth docutils literal notranslate"><span class="pre">fromstring()</span></code> is renamed to <code class="xref py py-meth docutils literal notranslate"><span class="pre">frombytes()</span></code> for clarity.</p></div></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="array.array.fromfile"><span class="sig-name descname"><span class="pre">fromfile</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">f</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">n</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#array.array.fromfile" title="Link to this definition">¶</a></dt><dd><p>Read <em>n</em> items (as machine values) from the <a class="reference internal" href="../glossary.html#term-file-object"><span class="xref std std-term">file object</span></a> <em>f</em> and appendthem to the end of the array. If less than <em>n</em> items are available,<a class="reference internal" href="exceptions.html#EOFError" title="EOFError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">EOFError</span></code></a> is raised, but the items that were available are stillinserted into the array.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="array.array.fromlist"><span class="sig-name descname"><span class="pre">fromlist</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">list</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#array.array.fromlist" title="Link to this definition">¶</a></dt><dd><p>Append items from the list. This is equivalent to <code class="docutils literal notranslate"><span class="pre">for</span> <span class="pre">x</span> <span class="pre">in</span> <span class="pre">list:</span><span class="pre">a.append(x)</span></code> except that if there is a type error, the array is unchanged.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="array.array.fromunicode"><span class="sig-name descname"><span class="pre">fromunicode</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">s</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#array.array.fromunicode" title="Link to this definition">¶</a></dt><dd><p>Extends this array with data from the given Unicode string.The array must have type code <code class="docutils literal notranslate"><span class="pre">'u'</span></code> or <code class="docutils literal notranslate"><span class="pre">'w'</span></code>; otherwise a <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> is raised.Use <code class="docutils literal notranslate"><span class="pre">array.frombytes(unicodestring.encode(enc))</span></code> to append Unicode data to anarray of some other type.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="array.array.index"><span class="sig-name descname"><span class="pre">index</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">x</span></span></em><span class="optional">[</span>, <em class="sig-param"><span class="n"><span class="pre">start</span></span></em><span class="optional">[</span>, <em class="sig-param"><span class="n"><span class="pre">stop</span></span></em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#array.array.index" title="Link to this definition">¶</a></dt><dd><p>Return the smallest <em>i</em> such that <em>i</em> is the index of the first occurrence of<em>x</em> in the array. The optional arguments <em>start</em> and <em>stop</em> can bespecified to search for <em>x</em> within a subsection of the array. Raise<a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> if <em>x</em> is not found.</p><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.10: </span>Added optional <em>start</em> and <em>stop</em> parameters.</p></div></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="array.array.insert"><span class="sig-name descname"><span class="pre">insert</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">i</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">x</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#array.array.insert" title="Link to this definition">¶</a></dt><dd><p>Insert a new item with value <em>x</em> in the array before position <em>i</em>. Negativevalues are treated as being relative to the end of the array.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="array.array.pop"><span class="sig-name descname"><span class="pre">pop</span></span><span class="sig-paren">(</span><span class="optional">[</span><em class="sig-param"><span class="n"><span class="pre">i</span></span></em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#array.array.pop" title="Link to this definition">¶</a></dt><dd><p>Removes the item with the index <em>i</em> from the array and returns it. The optionalargument defaults to <code class="docutils literal notranslate"><span class="pre">-1</span></code>, so that by default the last item is removed andreturned.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="array.array.remove"><span class="sig-name descname"><span class="pre">remove</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">x</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#array.array.remove" title="Link to this definition">¶</a></dt><dd><p>Remove the first occurrence of <em>x</em> from the array.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="array.array.clear"><span class="sig-name descname"><span class="pre">clear</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#array.array.clear" title="Link to this definition">¶</a></dt><dd><p>Remove all elements from the array.</p><div class="versionadded"><p><span class="versionmodified added">Added in version 3.13.</span></p></div></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="array.array.reverse"><span class="sig-name descname"><span class="pre">reverse</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#array.array.reverse" title="Link to this definition">¶</a></dt><dd><p>Reverse the order of the items in the array.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="array.array.tobytes"><span class="sig-name descname"><span class="pre">tobytes</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#array.array.tobytes" title="Link to this definition">¶</a></dt><dd><p>Convert the array to an array of machine values and return the bytesrepresentation (the same sequence of bytes that would be written to a file bythe <a class="reference internal" href="#array.array.tofile" title="array.array.tofile"><code class="xref py py-meth docutils literal notranslate"><span class="pre">tofile()</span></code></a> method.)</p><div class="versionadded"><p><span class="versionmodified added">Added in version 3.2: </span><code class="xref py py-meth docutils literal notranslate"><span class="pre">tostring()</span></code> is renamed to <code class="xref py py-meth docutils literal notranslate"><span class="pre">tobytes()</span></code> for clarity.</p></div></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="array.array.tofile"><span class="sig-name descname"><span class="pre">tofile</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">f</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#array.array.tofile" title="Link to this definition">¶</a></dt><dd><p>Write all items (as machine values) to the <a class="reference internal" href="../glossary.html#term-file-object"><span class="xref std std-term">file object</span></a> <em>f</em>.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="array.array.tolist"><span class="sig-name descname"><span class="pre">tolist</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#array.array.tolist" title="Link to this definition">¶</a></dt><dd><p>Convert the array to an ordinary list with the same items.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="array.array.tounicode"><span class="sig-name descname"><span class="pre">tounicode</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#array.array.tounicode" title="Link to this definition">¶</a></dt><dd><p>Convert the array to a Unicode string. The array must have a type <code class="docutils literal notranslate"><span class="pre">'u'</span></code> or <code class="docutils literal notranslate"><span class="pre">'w'</span></code>;otherwise a <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> is raised. Use <code class="docutils literal notranslate"><span class="pre">array.tobytes().decode(enc)</span></code> toobtain a Unicode string from an array of some other type.</p></dd></dl>
</dd></dl>
<p>The string representation of array objects has the form<code class="docutils literal notranslate"><span class="pre">array(typecode,</span> <span class="pre">initializer)</span></code>.The <em>initializer</em> is omitted if the array is empty, otherwise it isa Unicode string if the <em>typecode</em> is <code class="docutils literal notranslate"><span class="pre">'u'</span></code> or <code class="docutils literal notranslate"><span class="pre">'w'</span></code>, otherwise it isa list of numbers.The string representation is guaranteed to be able to be converted back to anarray with the same type and value using <a class="reference internal" href="functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a>, so long as the<a class="reference internal" href="#array.array" title="array.array"><code class="xref py py-class docutils literal notranslate"><span class="pre">array</span></code></a> class has been imported using <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">array</span> <span class="pre">import</span> <span class="pre">array</span></code>.Variables <code class="docutils literal notranslate"><span class="pre">inf</span></code> and <code class="docutils literal notranslate"><span class="pre">nan</span></code> must also be defined if it containscorresponding floating-point values.Examples:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">array</span><span class="p">(</span><span class="s1">'l'</span><span class="p">)</span><span class="n">array</span><span class="p">(</span><span class="s1">'w'</span><span class="p">,</span> <span class="s1">'hello </span><span class="se">\u2641</span><span class="s1">'</span><span class="p">)</span><span class="n">array</span><span class="p">(</span><span class="s1">'l'</span><span class="p">,</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">])</span><span class="n">array</span><span class="p">(</span><span class="s1">'d'</span><span class="p">,</span> <span class="p">[</span><span class="mf">1.0</span><span class="p">,</span> <span class="mf">2.0</span><span class="p">,</span> <span class="mf">3.14</span><span class="p">,</span> <span class="o">-</span><span class="n">inf</span><span class="p">,</span> <span class="n">nan</span><span class="p">])</span></pre></div></div><div class="admonition seealso"><p class="admonition-title">See also</p><dl class="simple"><dt>Module <a class="reference internal" href="struct.html#module-struct" title="struct: Interpret bytes as packed binary data."><code class="xref py py-mod docutils literal notranslate"><span class="pre">struct</span></code></a></dt><dd><p>Packing and unpacking of heterogeneous binary data.</p></dd><dt><a class="reference external" href="https://numpy.org/">NumPy</a></dt><dd><p>The NumPy package defines another array type.</p></dd></dl></div></section>
<div class="clearer"></div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="Main"> <div class="sphinxsidebarwrapper"> <div> <h4>Previous topic</h4> <p class="topless"><a href="bisect.html" title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">bisect</span></code> — Array bisection algorithm</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="weakref.html" title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">weakref</span></code> — Weak references</a></p> </div> <script> document.addEventListener('DOMContentLoaded', () => { const title = document.querySelector('meta[property="og:title"]').content; const elements = document.querySelectorAll('.improvepage'); const pageurl = window.location.href.split('?')[0]; elements.forEach(element => { const url = new URL(element.href.split('?')[0].replace("-nojs", "")); url.searchParams.set('pagetitle', title); url.searchParams.set('pageurl', pageurl); url.searchParams.set('pagesource', "library/array.rst"); element.href = url.toString(); }); }); </script> <div role="note" aria-label="source link"> <h3>This page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a bug</a></li> <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li> <li> <a href="https://github.com/python/cpython/blob/main/Doc/library/array.rst?plain=1" rel="nofollow">Show source </a> </li> </ul> </div> </div><div id="sidebarbutton" title="Collapse sidebar"><span>«</span></div>
</div> <div class="clearer"></div> </div> <div class="related" role="navigation" aria-label="Related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="weakref.html" title="weakref — Weak references" >next</a> |</li> <li class="right" > <a href="bisect.html" title="bisect — Array bisection algorithm" >previous</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.15.0a6 Documentation</a> » </li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="datatypes.html" >Data Types</a> »</li> <li class="nav-item nav-item-this"><a href=""><code class="xref py py-mod docutils literal notranslate"><span class="pre">array</span></code> — Efficient arrays of numeric values</a></li> <li class="right">
<div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box"> <input type="submit" value="Go"> </form> </div> | </li> <li class="right"><label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> |</li> </ul> </div> <div class="footer"> © <a href="../copyright.html">Copyright</a> 2001 Python Software Foundation. <br> This page is licensed under the Python Software Foundation License Version 2. <br> Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. <br> See <a href="/license.html">History and License</a> for more information.<br> <br>
The Python Software Foundation is a non-profit corporation.<a href="https://www.python.org/psf/donations/">Please donate.</a><br> <br> Last updated on Mar 10, 2026 (08:58 UTC). <a href="/bugs.html">Found a bug</a>? <br>
Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3. </div>
</body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354<!DOCTYPE html>
<html lang="en" data-content_root="../"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta property="og:title" content="asynchat — Asynchronous socket command/response handler" /><meta property="og:type" content="website" /><meta property="og:url" content="https://docs.python.org/3/library/asynchat.html" /><meta property="og:site_name" content="Python documentation" /><meta property="og:description" content="This module is no longer part of the Python standard library. It was removed in Python 3.12 after being deprecated in Python 3.6. The removal was decided in PEP 594. Applications should use the asy..." /><meta property="og:image:width" content="1146" /><meta property="og:image:height" content="600" /><meta property="og:image" content="https://docs.python.org/3.15/_images/social_previews/summary_library_asynchat_32364b6c.png" /><meta property="og:image:alt" content="This module is no longer part of the Python standard library. It was removed in Python 3.12 after being deprecated in Python 3.6. The removal was decided in PEP 594. Applications should use the asy..." /><meta name="description" content="This module is no longer part of the Python standard library. It was removed in Python 3.12 after being deprecated in Python 3.6. The removal was decided in PEP 594. Applications should use the asy..." /><meta name="twitter:card" content="summary_large_image" /><meta name="theme-color" content="#3776ab">
<title>asynchat — Asynchronous socket command/response handler — Python 3.15.0a6 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" /> <link rel="stylesheet" type="text/css" href="../_static/classic.css?v=234b1a7c" /> <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=89a2f22a" /> <link rel="stylesheet" type="text/css" href="../_static/profiling-sampling-visualization.css?v=0c2600ae" /> <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" /> <script src="../_static/documentation_options.js?v=6b7c9ff5"></script> <script src="../_static/doctools.js?v=9bcbadda"></script> <script src="../_static/sphinx_highlight.js?v=dc90522c"></script> <script src="../_static/profiling-sampling-visualization.js?v=9811ed04"></script> <script src="../_static/sidebar.js"></script> <link rel="search" type="application/opensearchdescription+xml" title="Search within Python 3.15.0a6 documentation" href="../_static/opensearch.xml"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="copyright" title="Copyright" href="../copyright.html" /> <link rel="next" title="asyncore — Asynchronous socket handler" href="asyncore.html" /> <link rel="prev" title="aifc — Read and write AIFF and AIFC files" href="aifc.html" /> <script defer file-types="bz2,epub,zip" data-domain="docs.python.org" src="https://analytics.python.org/js/script.file-downloads.outbound-links.js"></script> <link rel="canonical" href="https://docs.python.org/3/library/asynchat.html">
<style> @media only screen { table.full-width-table { width: 100%; } } </style><link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css"> <link rel="shortcut icon" type="image/png" href="../_static/py.svg"> <script type="text/javascript" src="../_static/copybutton.js"></script> <script type="text/javascript" src="../_static/menu.js"></script> <script type="text/javascript" src="../_static/search-focus.js"></script> <script type="text/javascript" src="../_static/themetoggle.js"></script> <script type="text/javascript" src="../_static/rtd_switcher.js"></script> <meta name="readthedocs-addons-api-version" content="1">
</head><body><div class="mobile-nav"> <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation" aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu"> <nav class="nav-content" role="navigation"> <label for="menuToggler" class="toggler__label"> <span></span> </label> <span class="nav-items-wrapper"> <a href="https://www.python.org/" class="nav-logo"> <img src="../_static/py.svg" alt="Python logo"> </a> <span class="version_switcher_placeholder"></span> <form role="search" class="search" action="../search.html" method="get"> <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon"> <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> </svg> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q"> <input type="submit" value="Go"> </form> </span> </nav> <div class="menu-wrapper"> <nav class="menu" role="navigation" aria-label="main navigation"> <div class="language_switcher_placeholder"></div> <label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> <div> <h4>Previous topic</h4> <p class="topless"><a href="aifc.html" title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">aifc</span></code> — Read and write AIFF and AIFC files</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="asyncore.html" title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">asyncore</span></code> — Asynchronous socket handler</a></p> </div> <script> document.addEventListener('DOMContentLoaded', () => { const title = document.querySelector('meta[property="og:title"]').content; const elements = document.querySelectorAll('.improvepage'); const pageurl = window.location.href.split('?')[0]; elements.forEach(element => { const url = new URL(element.href.split('?')[0].replace("-nojs", "")); url.searchParams.set('pagetitle', title); url.searchParams.set('pageurl', pageurl); url.searchParams.set('pagesource', "library/asynchat.rst"); element.href = url.toString(); }); }); </script> <div role="note" aria-label="source link"> <h3>This page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a bug</a></li> <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li> <li> <a href="https://github.com/python/cpython/blob/main/Doc/library/asynchat.rst?plain=1" rel="nofollow">Show source </a> </li> </ul> </div> </nav> </div></div>
<div class="related" role="navigation" aria-label="Related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="asyncore.html" title="asyncore — Asynchronous socket handler" accesskey="N">next</a> |</li> <li class="right" > <a href="aifc.html" title="aifc — Read and write AIFF and AIFC files" accesskey="P">previous</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.15.0a6 Documentation</a> » </li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="removed.html" accesskey="U">Removed Modules</a> »</li> <li class="nav-item nav-item-this"><a href=""><code class="xref py py-mod docutils literal notranslate"><span class="pre">asynchat</span></code> — Asynchronous socket command/response handler</a></li> <li class="right">
<div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box"> <input type="submit" value="Go"> </form> </div> | </li> <li class="right"><label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> |</li> </ul> </div>
<div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <section id="module-asynchat"><span id="asynchat-asynchronous-socket-command-response-handler"></span><h1><code class="xref py py-mod docutils literal notranslate"><span class="pre">asynchat</span></code> — Asynchronous socket command/response handler<a class="headerlink" href="#module-asynchat" title="Link to this heading">¶</a></h1><div class="deprecated-removed"><p><span class="versionmodified removed">Deprecated since version 3.6, removed in version 3.12.</span></p></div><p>This module is no longer part of the Python standard library.It was <a class="reference internal" href="../whatsnew/3.12.html#whatsnew312-removed"><span class="std std-ref">removed in Python 3.12</span></a> afterbeing deprecated in Python 3.6. The removal was decided in <span class="target" id="index-0"></span><a class="pep reference external" href="https://peps.python.org/pep-0594/"><strong>PEP 594</strong></a>.</p><p>Applications should use the <a class="reference internal" href="asyncio.html#module-asyncio" title="asyncio: Asynchronous I/O."><code class="xref py py-mod docutils literal notranslate"><span class="pre">asyncio</span></code></a> module instead.</p><p>The last version of Python that provided the <code class="xref py py-mod docutils literal notranslate"><span class="pre">asynchat</span></code> module was<a class="reference external" href="https://docs.python.org/3.11/library/asynchat.html">Python 3.11</a>.</p></section>
<div class="clearer"></div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="Main"> <div class="sphinxsidebarwrapper"> <div> <h4>Previous topic</h4> <p class="topless"><a href="aifc.html" title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">aifc</span></code> — Read and write AIFF and AIFC files</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="asyncore.html" title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">asyncore</span></code> — Asynchronous socket handler</a></p> </div> <script> document.addEventListener('DOMContentLoaded', () => { const title = document.querySelector('meta[property="og:title"]').content; const elements = document.querySelectorAll('.improvepage'); const pageurl = window.location.href.split('?')[0]; elements.forEach(element => { const url = new URL(element.href.split('?')[0].replace("-nojs", "")); url.searchParams.set('pagetitle', title); url.searchParams.set('pageurl', pageurl); url.searchParams.set('pagesource', "library/asynchat.rst"); element.href = url.toString(); }); }); </script> <div role="note" aria-label="source link"> <h3>This page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a bug</a></li> <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li> <li> <a href="https://github.com/python/cpython/blob/main/Doc/library/asynchat.rst?plain=1" rel="nofollow">Show source </a> </li> </ul> </div> </div><div id="sidebarbutton" title="Collapse sidebar"><span>«</span></div>
</div> <div class="clearer"></div> </div> <div class="related" role="navigation" aria-label="Related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="asyncore.html" title="asyncore — Asynchronous socket handler" >next</a> |</li> <li class="right" > <a href="aifc.html" title="aifc — Read and write AIFF and AIFC files" >previous</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.15.0a6 Documentation</a> » </li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="removed.html" >Removed Modules</a> »</li> <li class="nav-item nav-item-this"><a href=""><code class="xref py py-mod docutils literal notranslate"><span class="pre">asynchat</span></code> — Asynchronous socket command/response handler</a></li> <li class="right">
<div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box"> <input type="submit" value="Go"> </form> </div> | </li> <li class="right"><label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> |</li> </ul> </div> <div class="footer"> © <a href="../copyright.html">Copyright</a> 2001 Python Software Foundation. <br> This page is licensed under the Python Software Foundation License Version 2. <br> Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. <br> See <a href="/license.html">History and License</a> for more information.<br> <br>
The Python Software Foundation is a non-profit corporation.<a href="https://www.python.org/psf/donations/">Please donate.</a><br> <br> Last updated on Mar 10, 2026 (08:58 UTC). <a href="/bugs.html">Found a bug</a>? <br>
Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3. </div>
</body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597<!DOCTYPE html>
<html lang="en" data-content_root="../"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta property="og:title" content="High-level API Index" /><meta property="og:type" content="website" /><meta property="og:url" content="https://docs.python.org/3/library/asyncio-api-index.html" /><meta property="og:site_name" content="Python documentation" /><meta property="og:description" content="This page lists all high-level async/await enabled asyncio APIs. Tasks: Utilities to run asyncio programs, create Tasks, and await on multiple things with timeouts.,, run(), Create event loop, run ..." /><meta property="og:image:width" content="1146" /><meta property="og:image:height" content="600" /><meta property="og:image" content="https://docs.python.org/3.15/_images/social_previews/summary_library_asyncio-api-index_4ed6e667.png" /><meta property="og:image:alt" content="This page lists all high-level async/await enabled asyncio APIs. Tasks: Utilities to run asyncio programs, create Tasks, and await on multiple things with timeouts.,, run(), Create event loop, run ..." /><meta name="description" content="This page lists all high-level async/await enabled asyncio APIs. Tasks: Utilities to run asyncio programs, create Tasks, and await on multiple things with timeouts.,, run(), Create event loop, run ..." /><meta name="twitter:card" content="summary_large_image" /><meta name="theme-color" content="#3776ab">
<title>High-level API Index — Python 3.15.0a6 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" /> <link rel="stylesheet" type="text/css" href="../_static/classic.css?v=234b1a7c" /> <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=89a2f22a" /> <link rel="stylesheet" type="text/css" href="../_static/profiling-sampling-visualization.css?v=0c2600ae" /> <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" /> <script src="../_static/documentation_options.js?v=6b7c9ff5"></script> <script src="../_static/doctools.js?v=9bcbadda"></script> <script src="../_static/sphinx_highlight.js?v=dc90522c"></script> <script src="../_static/profiling-sampling-visualization.js?v=9811ed04"></script> <script src="../_static/sidebar.js"></script> <link rel="search" type="application/opensearchdescription+xml" title="Search within Python 3.15.0a6 documentation" href="../_static/opensearch.xml"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="copyright" title="Copyright" href="../copyright.html" /> <link rel="next" title="Low-level API Index" href="asyncio-llapi-index.html" /> <link rel="prev" title="Extending" href="asyncio-extending.html" /> <script defer file-types="bz2,epub,zip" data-domain="docs.python.org" src="https://analytics.python.org/js/script.file-downloads.outbound-links.js"></script> <link rel="canonical" href="https://docs.python.org/3/library/asyncio-api-index.html">
<style> @media only screen { table.full-width-table { width: 100%; } } </style><link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css"> <link rel="shortcut icon" type="image/png" href="../_static/py.svg"> <script type="text/javascript" src="../_static/copybutton.js"></script> <script type="text/javascript" src="../_static/menu.js"></script> <script type="text/javascript" src="../_static/search-focus.js"></script> <script type="text/javascript" src="../_static/themetoggle.js"></script> <script type="text/javascript" src="../_static/rtd_switcher.js"></script> <meta name="readthedocs-addons-api-version" content="1">
</head><body><div class="mobile-nav"> <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation" aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu"> <nav class="nav-content" role="navigation"> <label for="menuToggler" class="toggler__label"> <span></span> </label> <span class="nav-items-wrapper"> <a href="https://www.python.org/" class="nav-logo"> <img src="../_static/py.svg" alt="Python logo"> </a> <span class="version_switcher_placeholder"></span> <form role="search" class="search" action="../search.html" method="get"> <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon"> <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> </svg> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q"> <input type="submit" value="Go"> </form> </span> </nav> <div class="menu-wrapper"> <nav class="menu" role="navigation" aria-label="main navigation"> <div class="language_switcher_placeholder"></div> <label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> <div> <h3><a href="../contents.html">Table of Contents</a></h3> <ul><li><a class="reference internal" href="#">High-level API Index</a><ul><li><a class="reference internal" href="#tasks">Tasks</a></li><li><a class="reference internal" href="#queues">Queues</a></li><li><a class="reference internal" href="#subprocesses">Subprocesses</a></li><li><a class="reference internal" href="#streams">Streams</a></li><li><a class="reference internal" href="#synchronization">Synchronization</a></li><li><a class="reference internal" href="#exceptions">Exceptions</a></li></ul></li></ul>
</div> <div> <h4>Previous topic</h4> <p class="topless"><a href="asyncio-extending.html" title="previous chapter">Extending</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="asyncio-llapi-index.html" title="next chapter">Low-level API Index</a></p> </div> <script> document.addEventListener('DOMContentLoaded', () => { const title = document.querySelector('meta[property="og:title"]').content; const elements = document.querySelectorAll('.improvepage'); const pageurl = window.location.href.split('?')[0]; elements.forEach(element => { const url = new URL(element.href.split('?')[0].replace("-nojs", "")); url.searchParams.set('pagetitle', title); url.searchParams.set('pageurl', pageurl); url.searchParams.set('pagesource', "library/asyncio-api-index.rst"); element.href = url.toString(); }); }); </script> <div role="note" aria-label="source link"> <h3>This page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a bug</a></li> <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li> <li> <a href="https://github.com/python/cpython/blob/main/Doc/library/asyncio-api-index.rst?plain=1" rel="nofollow">Show source </a> </li> </ul> </div> </nav> </div></div>
<div class="related" role="navigation" aria-label="Related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="asyncio-llapi-index.html" title="Low-level API Index" accesskey="N">next</a> |</li> <li class="right" > <a href="asyncio-extending.html" title="Extending" accesskey="P">previous</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.15.0a6 Documentation</a> » </li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="ipc.html" >Networking and Interprocess Communication</a> »</li> <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> »</li> <li class="nav-item nav-item-this"><a href="">High-level API Index</a></li> <li class="right">
<div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box"> <input type="submit" value="Go"> </form> </div> | </li> <li class="right"><label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> |</li> </ul> </div>
<div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <section id="high-level-api-index"><h1>High-level API Index<a class="headerlink" href="#high-level-api-index" title="Link to this heading">¶</a></h1><p>This page lists all high-level async/await enabled asyncio APIs.</p><section id="tasks"><h2>Tasks<a class="headerlink" href="#tasks" title="Link to this heading">¶</a></h2><p>Utilities to run asyncio programs, create Tasks, andawait on multiple things with timeouts.</p><table class="full-width-table docutils align-default"><colgroup><col style="width: 50.0%" /><col style="width: 50.0%" /></colgroup><tbody><tr class="row-odd"><td><p><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">run()</span></code></a></p></td><td><p>Create event loop, run a coroutine, close the loop.</p></td></tr><tr class="row-even"><td><p><a class="reference internal" href="asyncio-runner.html#asyncio.Runner" title="asyncio.Runner"><code class="xref py py-class docutils literal notranslate"><span class="pre">Runner</span></code></a></p></td><td><p>A context manager that simplifies multiple async function calls.</p></td></tr><tr class="row-odd"><td><p><a class="reference internal" href="asyncio-task.html#asyncio.Task" title="asyncio.Task"><code class="xref py py-class docutils literal notranslate"><span class="pre">Task</span></code></a></p></td><td><p>Task object.</p></td></tr><tr class="row-even"><td><p><a class="reference internal" href="asyncio-task.html#asyncio.TaskGroup" title="asyncio.TaskGroup"><code class="xref py py-class docutils literal notranslate"><span class="pre">TaskGroup</span></code></a></p></td><td><p>A context manager that holds a group of tasks. Providesa convenient and reliable way to wait for all tasks in the group tofinish.</p></td></tr><tr class="row-odd"><td><p><a class="reference internal" href="asyncio-task.html#asyncio.create_task" title="asyncio.create_task"><code class="xref py py-func docutils literal notranslate"><span class="pre">create_task()</span></code></a></p></td><td><p>Start an asyncio Task, then returns it.</p></td></tr><tr class="row-even"><td><p><a class="reference internal" href="asyncio-task.html#asyncio.current_task" title="asyncio.current_task"><code class="xref py py-func docutils literal notranslate"><span class="pre">current_task()</span></code></a></p></td><td><p>Return the current Task.</p></td></tr><tr class="row-odd"><td><p><a class="reference internal" href="asyncio-task.html#asyncio.all_tasks" title="asyncio.all_tasks"><code class="xref py py-func docutils literal notranslate"><span class="pre">all_tasks()</span></code></a></p></td><td><p>Return all tasks that are not yet finished for an event loop.</p></td></tr><tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">await</span></code> <a class="reference internal" href="asyncio-task.html#asyncio.sleep" title="asyncio.sleep"><code class="xref py py-func docutils literal notranslate"><span class="pre">sleep()</span></code></a></p></td><td><p>Sleep for a number of seconds.</p></td></tr><tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">await</span></code> <a class="reference internal" href="asyncio-task.html#asyncio.gather" title="asyncio.gather"><code class="xref py py-func docutils literal notranslate"><span class="pre">gather()</span></code></a></p></td><td><p>Schedule and wait for things concurrently.</p></td></tr><tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">await</span></code> <a class="reference internal" href="asyncio-task.html#asyncio.wait_for" title="asyncio.wait_for"><code class="xref py py-func docutils literal notranslate"><span class="pre">wait_for()</span></code></a></p></td><td><p>Run with a timeout.</p></td></tr><tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">await</span></code> <a class="reference internal" href="asyncio-task.html#asyncio.shield" title="asyncio.shield"><code class="xref py py-func docutils literal notranslate"><span class="pre">shield()</span></code></a></p></td><td><p>Shield from cancellation.</p></td></tr><tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">await</span></code> <a class="reference internal" href="asyncio-task.html#asyncio.wait" title="asyncio.wait"><code class="xref py py-func docutils literal notranslate"><span class="pre">wait()</span></code></a></p></td><td><p>Monitor for completion.</p></td></tr><tr class="row-odd"><td><p><a class="reference internal" href="asyncio-task.html#asyncio.timeout" title="asyncio.timeout"><code class="xref py py-func docutils literal notranslate"><span class="pre">timeout()</span></code></a></p></td><td><p>Run with a timeout. Useful in cases when <code class="docutils literal notranslate"><span class="pre">wait_for</span></code> is not suitable.</p></td></tr><tr class="row-even"><td><p><a class="reference internal" href="asyncio-task.html#asyncio.to_thread" title="asyncio.to_thread"><code class="xref py py-func docutils literal notranslate"><span class="pre">to_thread()</span></code></a></p></td><td><p>Asynchronously run a function in a separate OS thread.</p></td></tr><tr class="row-odd"><td><p><a class="reference internal" href="asyncio-task.html#asyncio.run_coroutine_threadsafe" title="asyncio.run_coroutine_threadsafe"><code class="xref py py-func docutils literal notranslate"><span class="pre">run_coroutine_threadsafe()</span></code></a></p></td><td><p>Schedule a coroutine from another OS thread.</p></td></tr><tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">for</span> <span class="pre">in</span></code> <a class="reference internal" href="asyncio-task.html#asyncio.as_completed" title="asyncio.as_completed"><code class="xref py py-func docutils literal notranslate"><span class="pre">as_completed()</span></code></a></p></td><td><p>Monitor for completion with a <code class="docutils literal notranslate"><span class="pre">for</span></code> loop.</p></td></tr></tbody></table><p class="rubric">Examples</p><ul class="simple"><li><p><a class="reference internal" href="asyncio-task.html#asyncio-example-gather"><span class="std std-ref">Using asyncio.gather() to run things in parallel</span></a>.</p></li><li><p><a class="reference internal" href="asyncio-task.html#asyncio-example-waitfor"><span class="std std-ref">Using asyncio.wait_for() to enforce a timeout</span></a>.</p></li><li><p><a class="reference internal" href="asyncio-task.html#asyncio-example-task-cancel"><span class="std std-ref">Cancellation</span></a>.</p></li><li><p><a class="reference internal" href="asyncio-task.html#asyncio-example-sleep"><span class="std std-ref">Using asyncio.sleep()</span></a>.</p></li><li><p>See also the main <a class="reference internal" href="asyncio-task.html#coroutine"><span class="std std-ref">Tasks documentation page</span></a>.</p></li></ul></section><section id="queues"><h2>Queues<a class="headerlink" href="#queues" title="Link to this heading">¶</a></h2><p>Queues should be used to distribute work amongst multiple asyncio Tasks,implement connection pools, and pub/sub patterns.</p><table class="full-width-table docutils align-default"><colgroup><col style="width: 50.0%" /><col style="width: 50.0%" /></colgroup><tbody><tr class="row-odd"><td><p><a class="reference internal" href="asyncio-queue.html#asyncio.Queue" title="asyncio.Queue"><code class="xref py py-class docutils literal notranslate"><span class="pre">Queue</span></code></a></p></td><td><p>A FIFO queue.</p></td></tr><tr class="row-even"><td><p><a class="reference internal" href="asyncio-queue.html#asyncio.PriorityQueue" title="asyncio.PriorityQueue"><code class="xref py py-class docutils literal notranslate"><span class="pre">PriorityQueue</span></code></a></p></td><td><p>A priority queue.</p></td></tr><tr class="row-odd"><td><p><a class="reference internal" href="asyncio-queue.html#asyncio.LifoQueue" title="asyncio.LifoQueue"><code class="xref py py-class docutils literal notranslate"><span class="pre">LifoQueue</span></code></a></p></td><td><p>A LIFO queue.</p></td></tr></tbody></table><p class="rubric">Examples</p><ul class="simple"><li><p><a class="reference internal" href="asyncio-queue.html#asyncio-example-queue-dist"><span class="std std-ref">Using asyncio.Queue to distribute workload between severalTasks</span></a>.</p></li><li><p>See also the <a class="reference internal" href="asyncio-queue.html#asyncio-queues"><span class="std std-ref">Queues documentation page</span></a>.</p></li></ul></section><section id="subprocesses"><h2>Subprocesses<a class="headerlink" href="#subprocesses" title="Link to this heading">¶</a></h2><p>Utilities to spawn subprocesses and run shell commands.</p><table class="full-width-table docutils align-default"><colgroup><col style="width: 50.0%" /><col style="width: 50.0%" /></colgroup><tbody><tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">await</span></code> <a class="reference internal" href="asyncio-subprocess.html#asyncio.create_subprocess_exec" title="asyncio.create_subprocess_exec"><code class="xref py py-func docutils literal notranslate"><span class="pre">create_subprocess_exec()</span></code></a></p></td><td><p>Create a subprocess.</p></td></tr><tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">await</span></code> <a class="reference internal" href="asyncio-subprocess.html#asyncio.create_subprocess_shell" title="asyncio.create_subprocess_shell"><code class="xref py py-func docutils literal notranslate"><span class="pre">create_subprocess_shell()</span></code></a></p></td><td><p>Run a shell command.</p></td></tr></tbody></table><p class="rubric">Examples</p><ul class="simple"><li><p><a class="reference internal" href="asyncio-subprocess.html#asyncio-example-subprocess-shell"><span class="std std-ref">Executing a shell command</span></a>.</p></li><li><p>See also the <a class="reference internal" href="asyncio-subprocess.html#asyncio-subprocess"><span class="std std-ref">subprocess APIs</span></a>documentation.</p></li></ul></section><section id="streams"><h2>Streams<a class="headerlink" href="#streams" title="Link to this heading">¶</a></h2><p>High-level APIs to work with network IO.</p><table class="full-width-table docutils align-default"><colgroup><col style="width: 50.0%" /><col style="width: 50.0%" /></colgroup><tbody><tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">await</span></code> <a class="reference internal" href="asyncio-stream.html#asyncio.open_connection" title="asyncio.open_connection"><code class="xref py py-func docutils literal notranslate"><span class="pre">open_connection()</span></code></a></p></td><td><p>Establish a TCP connection.</p></td></tr><tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">await</span></code> <a class="reference internal" href="asyncio-stream.html#asyncio.open_unix_connection" title="asyncio.open_unix_connection"><code class="xref py py-func docutils literal notranslate"><span class="pre">open_unix_connection()</span></code></a></p></td><td><p>Establish a Unix socket connection.</p></td></tr><tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">await</span></code> <a class="reference internal" href="asyncio-stream.html#asyncio.start_server" title="asyncio.start_server"><code class="xref py py-func docutils literal notranslate"><span class="pre">start_server()</span></code></a></p></td><td><p>Start a TCP server.</p></td></tr><tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">await</span></code> <a class="reference internal" href="asyncio-stream.html#asyncio.start_unix_server" title="asyncio.start_unix_server"><code class="xref py py-func docutils literal notranslate"><span class="pre">start_unix_server()</span></code></a></p></td><td><p>Start a Unix socket server.</p></td></tr><tr class="row-odd"><td><p><a class="reference internal" href="asyncio-stream.html#asyncio.StreamReader" title="asyncio.StreamReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamReader</span></code></a></p></td><td><p>High-level async/await object to receive network data.</p></td></tr><tr class="row-even"><td><p><a class="reference internal" href="asyncio-stream.html#asyncio.StreamWriter" title="asyncio.StreamWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamWriter</span></code></a></p></td><td><p>High-level async/await object to send network data.</p></td></tr></tbody></table><p class="rubric">Examples</p><ul class="simple"><li><p><a class="reference internal" href="asyncio-stream.html#asyncio-example-stream"><span class="std std-ref">Example TCP client</span></a>.</p></li><li><p>See also the <a class="reference internal" href="asyncio-stream.html#asyncio-streams"><span class="std std-ref">streams APIs</span></a>documentation.</p></li></ul></section><section id="synchronization"><h2>Synchronization<a class="headerlink" href="#synchronization" title="Link to this heading">¶</a></h2><p>Threading-like synchronization primitives that can be used in Tasks.</p><table class="full-width-table docutils align-default"><colgroup><col style="width: 50.0%" /><col style="width: 50.0%" /></colgroup><tbody><tr class="row-odd"><td><p><a class="reference internal" href="asyncio-sync.html#asyncio.Lock" title="asyncio.Lock"><code class="xref py py-class docutils literal notranslate"><span class="pre">Lock</span></code></a></p></td><td><p>A mutex lock.</p></td></tr><tr class="row-even"><td><p><a class="reference internal" href="asyncio-sync.html#asyncio.Event" title="asyncio.Event"><code class="xref py py-class docutils literal notranslate"><span class="pre">Event</span></code></a></p></td><td><p>An event object.</p></td></tr><tr class="row-odd"><td><p><a class="reference internal" href="asyncio-sync.html#asyncio.Condition" title="asyncio.Condition"><code class="xref py py-class docutils literal notranslate"><span class="pre">Condition</span></code></a></p></td><td><p>A condition object.</p></td></tr><tr class="row-even"><td><p><a class="reference internal" href="asyncio-sync.html#asyncio.Semaphore" title="asyncio.Semaphore"><code class="xref py py-class docutils literal notranslate"><span class="pre">Semaphore</span></code></a></p></td><td><p>A semaphore.</p></td></tr><tr class="row-odd"><td><p><a class="reference internal" href="asyncio-sync.html#asyncio.BoundedSemaphore" title="asyncio.BoundedSemaphore"><code class="xref py py-class docutils literal notranslate"><span class="pre">BoundedSemaphore</span></code></a></p></td><td><p>A bounded semaphore.</p></td></tr><tr class="row-even"><td><p><a class="reference internal" href="asyncio-sync.html#asyncio.Barrier" title="asyncio.Barrier"><code class="xref py py-class docutils literal notranslate"><span class="pre">Barrier</span></code></a></p></td><td><p>A barrier object.</p></td></tr></tbody></table><p class="rubric">Examples</p><ul class="simple"><li><p><a class="reference internal" href="asyncio-sync.html#asyncio-example-sync-event"><span class="std std-ref">Using asyncio.Event</span></a>.</p></li><li><p><a class="reference internal" href="asyncio-sync.html#asyncio-example-barrier"><span class="std std-ref">Using asyncio.Barrier</span></a>.</p></li><li><p>See also the documentation of asyncio<a class="reference internal" href="asyncio-sync.html#asyncio-sync"><span class="std std-ref">synchronization primitives</span></a>.</p></li></ul></section><section id="exceptions"><h2>Exceptions<a class="headerlink" href="#exceptions" title="Link to this heading">¶</a></h2><table class="full-width-table docutils align-default"><colgroup><col style="width: 50.0%" /><col style="width: 50.0%" /></colgroup><tbody><tr class="row-odd"><td><p><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></p></td><td><p>Raised when a Task is cancelled. See also <a class="reference internal" href="asyncio-task.html#asyncio.Task.cancel" title="asyncio.Task.cancel"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Task.cancel()</span></code></a>.</p></td></tr><tr class="row-even"><td><p><a class="reference internal" href="asyncio-sync.html#asyncio.BrokenBarrierError" title="asyncio.BrokenBarrierError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">asyncio.BrokenBarrierError</span></code></a></p></td><td><p>Raised when a Barrier is broken. See also <a class="reference internal" href="asyncio-sync.html#asyncio.Barrier.wait" title="asyncio.Barrier.wait"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Barrier.wait()</span></code></a>.</p></td></tr></tbody></table><p class="rubric">Examples</p><ul class="simple"><li><p><a class="reference internal" href="asyncio-task.html#asyncio-example-task-cancel"><span class="std std-ref">Handling CancelledError to run code on cancellation request</span></a>.</p></li><li><p>See also the full list of<a class="reference internal" href="asyncio-exceptions.html#asyncio-exceptions"><span class="std std-ref">asyncio-specific exceptions</span></a>.</p></li></ul></section></section>
<div class="clearer"></div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="Main"> <div class="sphinxsidebarwrapper"> <div> <h3><a href="../contents.html">Table of Contents</a></h3> <ul><li><a class="reference internal" href="#">High-level API Index</a><ul><li><a class="reference internal" href="#tasks">Tasks</a></li><li><a class="reference internal" href="#queues">Queues</a></li><li><a class="reference internal" href="#subprocesses">Subprocesses</a></li><li><a class="reference internal" href="#streams">Streams</a></li><li><a class="reference internal" href="#synchronization">Synchronization</a></li><li><a class="reference internal" href="#exceptions">Exceptions</a></li></ul></li></ul>
</div> <div> <h4>Previous topic</h4> <p class="topless"><a href="asyncio-extending.html" title="previous chapter">Extending</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="asyncio-llapi-index.html" title="next chapter">Low-level API Index</a></p> </div> <script> document.addEventListener('DOMContentLoaded', () => { const title = document.querySelector('meta[property="og:title"]').content; const elements = document.querySelectorAll('.improvepage'); const pageurl = window.location.href.split('?')[0]; elements.forEach(element => { const url = new URL(element.href.split('?')[0].replace("-nojs", "")); url.searchParams.set('pagetitle', title); url.searchParams.set('pageurl', pageurl); url.searchParams.set('pagesource', "library/asyncio-api-index.rst"); element.href = url.toString(); }); }); </script> <div role="note" aria-label="source link"> <h3>This page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a bug</a></li> <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li> <li> <a href="https://github.com/python/cpython/blob/main/Doc/library/asyncio-api-index.rst?plain=1" rel="nofollow">Show source </a> </li> </ul> </div> </div><div id="sidebarbutton" title="Collapse sidebar"><span>«</span></div>
</div> <div class="clearer"></div> </div> <div class="related" role="navigation" aria-label="Related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="asyncio-llapi-index.html" title="Low-level API Index" >next</a> |</li> <li class="right" > <a href="asyncio-extending.html" title="Extending" >previous</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.15.0a6 Documentation</a> » </li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="ipc.html" >Networking and Interprocess Communication</a> »</li> <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> »</li> <li class="nav-item nav-item-this"><a href="">High-level API Index</a></li> <li class="right">
<div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box"> <input type="submit" value="Go"> </form> </div> | </li> <li class="right"><label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> |</li> </ul> </div> <div class="footer"> © <a href="../copyright.html">Copyright</a> 2001 Python Software Foundation. <br> This page is licensed under the Python Software Foundation License Version 2. <br> Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. <br> See <a href="/license.html">History and License</a> for more information.<br> <br>
The Python Software Foundation is a non-profit corporation.<a href="https://www.python.org/psf/donations/">Please donate.</a><br> <br> Last updated on Mar 10, 2026 (08:58 UTC). <a href="/bugs.html">Found a bug</a>? <br>
Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3. </div>
</body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587<!DOCTYPE html>
<html lang="en" data-content_root="../"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta property="og:title" content="Developing with asyncio" /><meta property="og:type" content="website" /><meta property="og:url" content="https://docs.python.org/3/library/asyncio-dev.html" /><meta property="og:site_name" content="Python documentation" /><meta property="og:description" content="Asynchronous programming is different from classic “sequential” programming. This page lists common mistakes and traps and explains how to avoid them. Debug Mode: By default asyncio runs in product..." /><meta property="og:image:width" content="1146" /><meta property="og:image:height" content="600" /><meta property="og:image" content="https://docs.python.org/3.15/_images/social_previews/summary_library_asyncio-dev_686102cd.png" /><meta property="og:image:alt" content="Asynchronous programming is different from classic “sequential” programming. This page lists common mistakes and traps and explains how to avoid them. Debug Mode: By default asyncio runs in product..." /><meta name="description" content="Asynchronous programming is different from classic “sequential” programming. This page lists common mistakes and traps and explains how to avoid them. Debug Mode: By default asyncio runs in product..." /><meta name="twitter:card" content="summary_large_image" /><meta name="theme-color" content="#3776ab">
<title>Developing with asyncio — Python 3.15.0a6 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" /> <link rel="stylesheet" type="text/css" href="../_static/classic.css?v=234b1a7c" /> <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=89a2f22a" /> <link rel="stylesheet" type="text/css" href="../_static/profiling-sampling-visualization.css?v=0c2600ae" /> <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" /> <script src="../_static/documentation_options.js?v=6b7c9ff5"></script> <script src="../_static/doctools.js?v=9bcbadda"></script> <script src="../_static/sphinx_highlight.js?v=dc90522c"></script> <script src="../_static/profiling-sampling-visualization.js?v=9811ed04"></script> <script src="../_static/sidebar.js"></script> <link rel="search" type="application/opensearchdescription+xml" title="Search within Python 3.15.0a6 documentation" href="../_static/opensearch.xml"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="copyright" title="Copyright" href="../copyright.html" /> <link rel="next" title="socket — Low-level networking interface" href="socket.html" /> <link rel="prev" title="Low-level API Index" href="asyncio-llapi-index.html" /> <script defer file-types="bz2,epub,zip" data-domain="docs.python.org" src="https://analytics.python.org/js/script.file-downloads.outbound-links.js"></script> <link rel="canonical" href="https://docs.python.org/3/library/asyncio-dev.html">
<style> @media only screen { table.full-width-table { width: 100%; } } </style><link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css"> <link rel="shortcut icon" type="image/png" href="../_static/py.svg"> <script type="text/javascript" src="../_static/copybutton.js"></script> <script type="text/javascript" src="../_static/menu.js"></script> <script type="text/javascript" src="../_static/search-focus.js"></script> <script type="text/javascript" src="../_static/themetoggle.js"></script> <script type="text/javascript" src="../_static/rtd_switcher.js"></script> <meta name="readthedocs-addons-api-version" content="1">
</head><body><div class="mobile-nav"> <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation" aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu"> <nav class="nav-content" role="navigation"> <label for="menuToggler" class="toggler__label"> <span></span> </label> <span class="nav-items-wrapper"> <a href="https://www.python.org/" class="nav-logo"> <img src="../_static/py.svg" alt="Python logo"> </a> <span class="version_switcher_placeholder"></span> <form role="search" class="search" action="../search.html" method="get"> <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon"> <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> </svg> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q"> <input type="submit" value="Go"> </form> </span> </nav> <div class="menu-wrapper"> <nav class="menu" role="navigation" aria-label="main navigation"> <div class="language_switcher_placeholder"></div> <label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> <div> <h3><a href="../contents.html">Table of Contents</a></h3> <ul><li><a class="reference internal" href="#">Developing with asyncio</a><ul><li><a class="reference internal" href="#debug-mode">Debug Mode</a></li><li><a class="reference internal" href="#concurrency-and-multithreading">Concurrency and Multithreading</a></li><li><a class="reference internal" href="#running-blocking-code">Running Blocking Code</a></li><li><a class="reference internal" href="#logging">Logging</a></li><li><a class="reference internal" href="#detect-never-awaited-coroutines">Detect never-awaited coroutines</a></li><li><a class="reference internal" href="#detect-never-retrieved-exceptions">Detect never-retrieved exceptions</a></li></ul></li></ul>
</div> <div> <h4>Previous topic</h4> <p class="topless"><a href="asyncio-llapi-index.html" title="previous chapter">Low-level API Index</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="socket.html" title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code> — Low-level networking interface</a></p> </div> <script> document.addEventListener('DOMContentLoaded', () => { const title = document.querySelector('meta[property="og:title"]').content; const elements = document.querySelectorAll('.improvepage'); const pageurl = window.location.href.split('?')[0]; elements.forEach(element => { const url = new URL(element.href.split('?')[0].replace("-nojs", "")); url.searchParams.set('pagetitle', title); url.searchParams.set('pageurl', pageurl); url.searchParams.set('pagesource', "library/asyncio-dev.rst"); element.href = url.toString(); }); }); </script> <div role="note" aria-label="source link"> <h3>This page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a bug</a></li> <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li> <li> <a href="https://github.com/python/cpython/blob/main/Doc/library/asyncio-dev.rst?plain=1" rel="nofollow">Show source </a> </li> </ul> </div> </nav> </div></div>
<div class="related" role="navigation" aria-label="Related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="socket.html" title="socket — Low-level networking interface" accesskey="N">next</a> |</li> <li class="right" > <a href="asyncio-llapi-index.html" title="Low-level API Index" accesskey="P">previous</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.15.0a6 Documentation</a> » </li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="ipc.html" >Networking and Interprocess Communication</a> »</li> <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> »</li> <li class="nav-item nav-item-this"><a href="">Developing with asyncio</a></li> <li class="right">
<div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box"> <input type="submit" value="Go"> </form> </div> | </li> <li class="right"><label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> |</li> </ul> </div>
<div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <section id="developing-with-asyncio"><span id="asyncio-dev"></span><h1>Developing with asyncio<a class="headerlink" href="#developing-with-asyncio" title="Link to this heading">¶</a></h1><p>Asynchronous programming is different from classic “sequential”programming.</p><p>This page lists common mistakes and traps and explains howto avoid them.</p><section id="debug-mode"><span id="asyncio-debug-mode"></span><h2>Debug Mode<a class="headerlink" href="#debug-mode" title="Link to this heading">¶</a></h2><p>By default asyncio runs in production mode. In order to easethe development asyncio has a <em>debug mode</em>.</p><p>There are several ways to enable asyncio debug mode:</p><ul class="simple"><li><p>Setting the <span class="target" id="index-0"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONASYNCIODEBUG"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONASYNCIODEBUG</span></code></a> environment variable to <code class="docutils literal notranslate"><span class="pre">1</span></code>.</p></li><li><p>Using the <a class="reference internal" href="devmode.html#devmode"><span class="std std-ref">Python Development Mode</span></a>.</p></li><li><p>Passing <code class="docutils literal notranslate"><span class="pre">debug=True</span></code> to <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>.</p></li><li><p>Calling <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.set_debug" title="asyncio.loop.set_debug"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.set_debug()</span></code></a>.</p></li></ul><p>In addition to enabling the debug mode, consider also:</p><ul><li><p>setting the log level of the <a class="reference internal" href="#asyncio-logger"><span class="std std-ref">asyncio logger</span></a> to<a class="reference internal" href="logging.html#logging.DEBUG" title="logging.DEBUG"><code class="xref py py-const docutils literal notranslate"><span class="pre">logging.DEBUG</span></code></a>, for example the following snippet of codecan be run at startup of the application:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">logging</span><span class="o">.</span><span class="n">basicConfig</span><span class="p">(</span><span class="n">level</span><span class="o">=</span><span class="n">logging</span><span class="o">.</span><span class="n">DEBUG</span><span class="p">)</span></pre></div></div></li><li><p>configuring the <a class="reference internal" href="warnings.html#module-warnings" title="warnings: Issue warning messages and control their disposition."><code class="xref py py-mod docutils literal notranslate"><span class="pre">warnings</span></code></a> module to display<a class="reference internal" href="exceptions.html#ResourceWarning" title="ResourceWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ResourceWarning</span></code></a> warnings. One way of doing that is byusing the <a class="reference internal" href="../using/cmdline.html#cmdoption-W"><code class="xref std std-option docutils literal notranslate"><span class="pre">-W</span></code></a> <code class="docutils literal notranslate"><span class="pre">default</span></code> command line option.</p></li></ul><p>When the debug mode is enabled:</p><ul class="simple"><li><p>Many non-threadsafe asyncio APIs (such as <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.call_soon" title="asyncio.loop.call_soon"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.call_soon()</span></code></a> and<a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.call_at" title="asyncio.loop.call_at"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.call_at()</span></code></a> methods) raise an exception if they are calledfrom a wrong thread.</p></li><li><p>The execution time of the I/O selector is logged if it takes too long toperform an I/O operation.</p></li><li><p>Callbacks taking longer than 100 milliseconds are logged. The<a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.slow_callback_duration" title="asyncio.loop.slow_callback_duration"><code class="xref py py-attr docutils literal notranslate"><span class="pre">loop.slow_callback_duration</span></code></a> attribute can be used to set theminimum execution duration in seconds that is considered “slow”.</p></li></ul></section><section id="concurrency-and-multithreading"><span id="asyncio-multithreading"></span><h2>Concurrency and Multithreading<a class="headerlink" href="#concurrency-and-multithreading" title="Link to this heading">¶</a></h2><p>An event loop runs in a thread (typically the main thread) and executesall callbacks and Tasks in its thread. While a Task is running in theevent loop, no other Tasks can run in the same thread. When a Taskexecutes an <code class="docutils literal notranslate"><span class="pre">await</span></code> expression, the running Task gets suspended, andthe event loop executes the next Task.</p><p>To schedule a <a class="reference internal" href="../glossary.html#term-callback"><span class="xref std std-term">callback</span></a> from another OS thread, the<a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.call_soon_threadsafe" title="asyncio.loop.call_soon_threadsafe"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.call_soon_threadsafe()</span></code></a> method should be used. Example:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">loop</span><span class="o">.</span><span class="n">call_soon_threadsafe</span><span class="p">(</span><span class="n">callback</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">)</span></pre></div></div><p>Almost all asyncio objects are not thread safe, which is typicallynot a problem unless there is code that works with them from outsideof a Task or a callback. If there’s a need for such code to call alow-level asyncio API, the <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.call_soon_threadsafe" title="asyncio.loop.call_soon_threadsafe"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.call_soon_threadsafe()</span></code></a> methodshould be used, e.g.:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">loop</span><span class="o">.</span><span class="n">call_soon_threadsafe</span><span class="p">(</span><span class="n">fut</span><span class="o">.</span><span class="n">cancel</span><span class="p">)</span></pre></div></div><p>To schedule a coroutine object from a different OS thread, the<a class="reference internal" href="asyncio-task.html#asyncio.run_coroutine_threadsafe" title="asyncio.run_coroutine_threadsafe"><code class="xref py py-func docutils literal notranslate"><span class="pre">run_coroutine_threadsafe()</span></code></a> function should be used. It returns 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 access the result:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">coro_func</span><span class="p">():</span> <span class="k">return</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> <span class="mi">42</span><span class="p">)</span>
<span class="c1"># Later in another OS thread:</span>
<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_func</span><span class="p">(),</span> <span class="n">loop</span><span class="p">)</span><span class="c1"># Wait for the result:</span><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></pre></div></div><p>To handle signals the event loop must berun in the main thread.</p><p>The <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> method can be used with a<a class="reference internal" href="concurrent.futures.html#concurrent.futures.ThreadPoolExecutor" title="concurrent.futures.ThreadPoolExecutor"><code class="xref py py-class docutils literal notranslate"><span class="pre">concurrent.futures.ThreadPoolExecutor</span></code></a> or<a class="reference internal" href="concurrent.futures.html#concurrent.futures.InterpreterPoolExecutor" title="concurrent.futures.InterpreterPoolExecutor"><code class="xref py py-class docutils literal notranslate"><span class="pre">InterpreterPoolExecutor</span></code></a> to executeblocking code in a different OS thread without blocking the OS threadthat the event loop runs in.</p><p>There is currently no way to schedule coroutines or callbacks directlyfrom a different process (such as one started with<a class="reference internal" href="multiprocessing.html#module-multiprocessing" title="multiprocessing: Process-based parallelism."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing</span></code></a>). The <a class="reference internal" href="asyncio-eventloop.html#asyncio-event-loop-methods"><span class="std std-ref">Event Loop Methods</span></a>section lists APIs that can read from pipes and watch file descriptorswithout blocking the event loop. In addition, asyncio’s<a class="reference internal" href="asyncio-subprocess.html#asyncio-subprocess"><span class="std std-ref">Subprocess</span></a> APIs provide a way to start aprocess and communicate with it from the event loop. Lastly, theaforementioned <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> method can also be usedwith a <a class="reference internal" href="concurrent.futures.html#concurrent.futures.ProcessPoolExecutor" title="concurrent.futures.ProcessPoolExecutor"><code class="xref py py-class docutils literal notranslate"><span class="pre">concurrent.futures.ProcessPoolExecutor</span></code></a> to executecode in a different process.</p></section><section id="running-blocking-code"><span id="asyncio-handle-blocking"></span><h2>Running Blocking Code<a class="headerlink" href="#running-blocking-code" title="Link to this heading">¶</a></h2><p>Blocking (CPU-bound) code should not be called directly. For example,if a function performs a CPU-intensive calculation for 1 second,all concurrent asyncio Tasks and IO operations would be delayedby 1 second.</p><p>An executor can be used to run a task in a different thread,including in a different interpreter, or even ina different process to avoid blocking the OS thread with theevent loop. See the <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> method for moredetails.</p></section><section id="logging"><span id="asyncio-logger"></span><h2>Logging<a class="headerlink" href="#logging" title="Link to this heading">¶</a></h2><p>asyncio uses the <a class="reference internal" href="logging.html#module-logging" title="logging: Flexible event logging system for applications."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging</span></code></a> module and all logging is performedvia the <code class="docutils literal notranslate"><span class="pre">"asyncio"</span></code> logger.</p><p>The default log level is <a class="reference internal" href="logging.html#logging.INFO" title="logging.INFO"><code class="xref py py-const docutils literal notranslate"><span class="pre">logging.INFO</span></code></a>, which can be easilyadjusted:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s2">"asyncio"</span><span class="p">)</span><span class="o">.</span><span class="n">setLevel</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">WARNING</span><span class="p">)</span></pre></div></div><p>Network logging can block the event loop. It is recommended to usea separate thread for handling logs or use non-blocking IO. For example,see <a class="reference internal" href="../howto/logging-cookbook.html#blocking-handlers"><span class="std std-ref">Dealing with handlers that block</span></a>.</p></section><section id="detect-never-awaited-coroutines"><span id="asyncio-coroutine-not-scheduled"></span><h2>Detect never-awaited coroutines<a class="headerlink" href="#detect-never-awaited-coroutines" title="Link to this heading">¶</a></h2><p>When a coroutine function is called, but not awaited(e.g. <code class="docutils literal notranslate"><span class="pre">coro()</span></code> instead of <code class="docutils literal notranslate"><span class="pre">await</span> <span class="pre">coro()</span></code>)or the coroutine is not scheduled with <a class="reference internal" href="asyncio-task.html#asyncio.create_task" title="asyncio.create_task"><code class="xref py py-meth docutils literal notranslate"><span class="pre">asyncio.create_task()</span></code></a>, asynciowill emit a <a class="reference internal" href="exceptions.html#RuntimeWarning" title="RuntimeWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeWarning</span></code></a>:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span><span class="w"> </span><span class="nn">asyncio</span>
<span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">test</span><span class="p">():</span> <span class="nb">print</span><span class="p">(</span><span class="s2">"never scheduled"</span><span class="p">)</span>
<span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">main</span><span class="p">():</span> <span class="n">test</span><span class="p">()</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></pre></div></div><p>Output:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">test</span><span class="o">.</span><span class="n">py</span><span class="p">:</span><span class="mi">7</span><span class="p">:</span> <span class="ne">RuntimeWarning</span><span class="p">:</span> <span class="n">coroutine</span> <span class="s1">'test'</span> <span class="n">was</span> <span class="n">never</span> <span class="n">awaited</span> <span class="n">test</span><span class="p">()</span></pre></div></div><p>Output in debug mode:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">test</span><span class="o">.</span><span class="n">py</span><span class="p">:</span><span class="mi">7</span><span class="p">:</span> <span class="ne">RuntimeWarning</span><span class="p">:</span> <span class="n">coroutine</span> <span class="s1">'test'</span> <span class="n">was</span> <span class="n">never</span> <span class="n">awaited</span><span class="n">Coroutine</span> <span class="n">created</span> <span class="n">at</span> <span class="p">(</span><span class="n">most</span> <span class="n">recent</span> <span class="n">call</span> <span class="n">last</span><span class="p">)</span> <span class="n">File</span> <span class="s2">"../t.py"</span><span class="p">,</span> <span class="n">line</span> <span class="mi">9</span><span class="p">,</span> <span class="ow">in</span> <span class="o"><</span><span class="n">module</span><span class="o">></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> <span class="n">debug</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="o"><</span> <span class="o">..</span> <span class="o">></span>
<span class="n">File</span> <span class="s2">"../t.py"</span><span class="p">,</span> <span class="n">line</span> <span class="mi">7</span><span class="p">,</span> <span class="ow">in</span> <span class="n">main</span> <span class="n">test</span><span class="p">()</span> <span class="n">test</span><span class="p">()</span></pre></div></div><p>The usual fix is to either await the coroutine or call the<a class="reference internal" href="asyncio-task.html#asyncio.create_task" title="asyncio.create_task"><code class="xref py py-meth docutils literal notranslate"><span class="pre">asyncio.create_task()</span></code></a> function:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">main</span><span class="p">():</span> <span class="k">await</span> <span class="n">test</span><span class="p">()</span></pre></div></div></section><section id="detect-never-retrieved-exceptions"><h2>Detect never-retrieved exceptions<a class="headerlink" href="#detect-never-retrieved-exceptions" title="Link to this heading">¶</a></h2><p>If a <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> is called but the Future object isnever awaited on, the exception would never be propagated to theuser code. In this case, asyncio would emit a log message when theFuture object is garbage collected.</p><p>Example of an unhandled exception:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span><span class="w"> </span><span class="nn">asyncio</span>
<span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">bug</span><span class="p">():</span> <span class="k">raise</span> <span class="ne">Exception</span><span class="p">(</span><span class="s2">"not consumed"</span><span class="p">)</span>
<span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">main</span><span class="p">():</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">create_task</span><span class="p">(</span><span class="n">bug</span><span class="p">())</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></pre></div></div><p>Output:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">Task</span> <span class="n">exception</span> <span class="n">was</span> <span class="n">never</span> <span class="n">retrieved</span><span class="n">future</span><span class="p">:</span> <span class="o"><</span><span class="n">Task</span> <span class="n">finished</span> <span class="n">coro</span><span class="o">=<</span><span class="n">bug</span><span class="p">()</span> <span class="n">done</span><span class="p">,</span> <span class="n">defined</span> <span class="n">at</span> <span class="n">test</span><span class="o">.</span><span class="n">py</span><span class="p">:</span><span class="mi">3</span><span class="o">></span> <span class="n">exception</span><span class="o">=</span><span class="ne">Exception</span><span class="p">(</span><span class="s1">'not consumed'</span><span class="p">)</span><span class="o">></span>
<span class="n">Traceback</span> <span class="p">(</span><span class="n">most</span> <span class="n">recent</span> <span class="n">call</span> <span class="n">last</span><span class="p">):</span> <span class="n">File</span> <span class="s2">"test.py"</span><span class="p">,</span> <span class="n">line</span> <span class="mi">4</span><span class="p">,</span> <span class="ow">in</span> <span class="n">bug</span> <span class="k">raise</span> <span class="ne">Exception</span><span class="p">(</span><span class="s2">"not consumed"</span><span class="p">)</span><span class="ne">Exception</span><span class="p">:</span> <span class="ow">not</span> <span class="n">consumed</span></pre></div></div><p><a class="reference internal" href="#asyncio-debug-mode"><span class="std std-ref">Enable the debug mode</span></a> to get thetraceback where the task was created:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></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> <span class="n">debug</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span></pre></div></div><p>Output in debug mode:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">Task</span> <span class="n">exception</span> <span class="n">was</span> <span class="n">never</span> <span class="n">retrieved</span><span class="n">future</span><span class="p">:</span> <span class="o"><</span><span class="n">Task</span> <span class="n">finished</span> <span class="n">coro</span><span class="o">=<</span><span class="n">bug</span><span class="p">()</span> <span class="n">done</span><span class="p">,</span> <span class="n">defined</span> <span class="n">at</span> <span class="n">test</span><span class="o">.</span><span class="n">py</span><span class="p">:</span><span class="mi">3</span><span class="o">></span> <span class="n">exception</span><span class="o">=</span><span class="ne">Exception</span><span class="p">(</span><span class="s1">'not consumed'</span><span class="p">)</span> <span class="n">created</span> <span class="n">at</span> <span class="n">asyncio</span><span class="o">/</span><span class="n">tasks</span><span class="o">.</span><span class="n">py</span><span class="p">:</span><span class="mi">321</span><span class="o">></span>
<span class="n">source_traceback</span><span class="p">:</span> <span class="n">Object</span> <span class="n">created</span> <span class="n">at</span> <span class="p">(</span><span class="n">most</span> <span class="n">recent</span> <span class="n">call</span> <span class="n">last</span><span class="p">):</span> <span class="n">File</span> <span class="s2">"../t.py"</span><span class="p">,</span> <span class="n">line</span> <span class="mi">9</span><span class="p">,</span> <span class="ow">in</span> <span class="o"><</span><span class="n">module</span><span class="o">></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> <span class="n">debug</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="o"><</span> <span class="o">..</span> <span class="o">></span>
<span class="n">Traceback</span> <span class="p">(</span><span class="n">most</span> <span class="n">recent</span> <span class="n">call</span> <span class="n">last</span><span class="p">):</span> <span class="n">File</span> <span class="s2">"../t.py"</span><span class="p">,</span> <span class="n">line</span> <span class="mi">4</span><span class="p">,</span> <span class="ow">in</span> <span class="n">bug</span> <span class="k">raise</span> <span class="ne">Exception</span><span class="p">(</span><span class="s2">"not consumed"</span><span class="p">)</span><span class="ne">Exception</span><span class="p">:</span> <span class="ow">not</span> <span class="n">consumed</span></pre></div></div></section></section>
<div class="clearer"></div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="Main"> <div class="sphinxsidebarwrapper"> <div> <h3><a href="../contents.html">Table of Contents</a></h3> <ul><li><a class="reference internal" href="#">Developing with asyncio</a><ul><li><a class="reference internal" href="#debug-mode">Debug Mode</a></li><li><a class="reference internal" href="#concurrency-and-multithreading">Concurrency and Multithreading</a></li><li><a class="reference internal" href="#running-blocking-code">Running Blocking Code</a></li><li><a class="reference internal" href="#logging">Logging</a></li><li><a class="reference internal" href="#detect-never-awaited-coroutines">Detect never-awaited coroutines</a></li><li><a class="reference internal" href="#detect-never-retrieved-exceptions">Detect never-retrieved exceptions</a></li></ul></li></ul>
</div> <div> <h4>Previous topic</h4> <p class="topless"><a href="asyncio-llapi-index.html" title="previous chapter">Low-level API Index</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="socket.html" title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code> — Low-level networking interface</a></p> </div> <script> document.addEventListener('DOMContentLoaded', () => { const title = document.querySelector('meta[property="og:title"]').content; const elements = document.querySelectorAll('.improvepage'); const pageurl = window.location.href.split('?')[0]; elements.forEach(element => { const url = new URL(element.href.split('?')[0].replace("-nojs", "")); url.searchParams.set('pagetitle', title); url.searchParams.set('pageurl', pageurl); url.searchParams.set('pagesource', "library/asyncio-dev.rst"); element.href = url.toString(); }); }); </script> <div role="note" aria-label="source link"> <h3>This page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a bug</a></li> <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li> <li> <a href="https://github.com/python/cpython/blob/main/Doc/library/asyncio-dev.rst?plain=1" rel="nofollow">Show source </a> </li> </ul> </div> </div><div id="sidebarbutton" title="Collapse sidebar"><span>«</span></div>
</div> <div class="clearer"></div> </div> <div class="related" role="navigation" aria-label="Related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="socket.html" title="socket — Low-level networking interface" >next</a> |</li> <li class="right" > <a href="asyncio-llapi-index.html" title="Low-level API Index" >previous</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.15.0a6 Documentation</a> » </li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="ipc.html" >Networking and Interprocess Communication</a> »</li> <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> »</li> <li class="nav-item nav-item-this"><a href="">Developing with asyncio</a></li> <li class="right">
<div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box"> <input type="submit" value="Go"> </form> </div> | </li> <li class="right"><label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> |</li> </ul> </div> <div class="footer"> © <a href="../copyright.html">Copyright</a> 2001 Python Software Foundation. <br> This page is licensed under the Python Software Foundation License Version 2. <br> Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. <br> See <a href="/license.html">History and License</a> for more information.<br> <br>
The Python Software Foundation is a non-profit corporation.<a href="https://www.python.org/psf/donations/">Please donate.</a><br> <br> Last updated on Mar 10, 2026 (08:58 UTC). <a href="/bugs.html">Found a bug</a>? <br>
Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3. </div>
</body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420<!DOCTYPE html>
<html lang="en" data-content_root="../"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta property="og:title" content="Exceptions" /><meta property="og:type" content="website" /><meta property="og:url" content="https://docs.python.org/3/library/asyncio-exceptions.html" /><meta property="og:site_name" content="Python documentation" /><meta property="og:description" content="Source code: Lib/asyncio/exceptions.py" /><meta property="og:image:width" content="1146" /><meta property="og:image:height" content="600" /><meta property="og:image" content="https://docs.python.org/3.15/_images/social_previews/summary_library_asyncio-exceptions_4b9646d1.png" /><meta property="og:image:alt" content="Source code: Lib/asyncio/exceptions.py" /><meta name="description" content="Source code: Lib/asyncio/exceptions.py" /><meta name="twitter:card" content="summary_large_image" /><meta name="theme-color" content="#3776ab">
<title>Exceptions — Python 3.15.0a6 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" /> <link rel="stylesheet" type="text/css" href="../_static/classic.css?v=234b1a7c" /> <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=89a2f22a" /> <link rel="stylesheet" type="text/css" href="../_static/profiling-sampling-visualization.css?v=0c2600ae" /> <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" /> <script src="../_static/documentation_options.js?v=6b7c9ff5"></script> <script src="../_static/doctools.js?v=9bcbadda"></script> <script src="../_static/sphinx_highlight.js?v=dc90522c"></script> <script src="../_static/profiling-sampling-visualization.js?v=9811ed04"></script> <script src="../_static/sidebar.js"></script> <link rel="search" type="application/opensearchdescription+xml" title="Search within Python 3.15.0a6 documentation" href="../_static/opensearch.xml"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="copyright" title="Copyright" href="../copyright.html" /> <link rel="next" title="Call Graph Introspection" href="asyncio-graph.html" /> <link rel="prev" title="Queues" href="asyncio-queue.html" /> <script defer file-types="bz2,epub,zip" data-domain="docs.python.org" src="https://analytics.python.org/js/script.file-downloads.outbound-links.js"></script> <link rel="canonical" href="https://docs.python.org/3/library/asyncio-exceptions.html">
<style> @media only screen { table.full-width-table { width: 100%; } } </style><link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css"> <link rel="shortcut icon" type="image/png" href="../_static/py.svg"> <script type="text/javascript" src="../_static/copybutton.js"></script> <script type="text/javascript" src="../_static/menu.js"></script> <script type="text/javascript" src="../_static/search-focus.js"></script> <script type="text/javascript" src="../_static/themetoggle.js"></script> <script type="text/javascript" src="../_static/rtd_switcher.js"></script> <meta name="readthedocs-addons-api-version" content="1">
</head><body><div class="mobile-nav"> <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation" aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu"> <nav class="nav-content" role="navigation"> <label for="menuToggler" class="toggler__label"> <span></span> </label> <span class="nav-items-wrapper"> <a href="https://www.python.org/" class="nav-logo"> <img src="../_static/py.svg" alt="Python logo"> </a> <span class="version_switcher_placeholder"></span> <form role="search" class="search" action="../search.html" method="get"> <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon"> <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> </svg> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q"> <input type="submit" value="Go"> </form> </span> </nav> <div class="menu-wrapper"> <nav class="menu" role="navigation" aria-label="main navigation"> <div class="language_switcher_placeholder"></div> <label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> <div> <h4>Previous topic</h4> <p class="topless"><a href="asyncio-queue.html" title="previous chapter">Queues</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="asyncio-graph.html" title="next chapter">Call Graph Introspection</a></p> </div> <script> document.addEventListener('DOMContentLoaded', () => { const title = document.querySelector('meta[property="og:title"]').content; const elements = document.querySelectorAll('.improvepage'); const pageurl = window.location.href.split('?')[0]; elements.forEach(element => { const url = new URL(element.href.split('?')[0].replace("-nojs", "")); url.searchParams.set('pagetitle', title); url.searchParams.set('pageurl', pageurl); url.searchParams.set('pagesource', "library/asyncio-exceptions.rst"); element.href = url.toString(); }); }); </script> <div role="note" aria-label="source link"> <h3>This page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a bug</a></li> <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li> <li> <a href="https://github.com/python/cpython/blob/main/Doc/library/asyncio-exceptions.rst?plain=1" rel="nofollow">Show source </a> </li> </ul> </div> </nav> </div></div>
<div class="related" role="navigation" aria-label="Related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="asyncio-graph.html" title="Call Graph Introspection" accesskey="N">next</a> |</li> <li class="right" > <a href="asyncio-queue.html" title="Queues" accesskey="P">previous</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.15.0a6 Documentation</a> » </li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="ipc.html" >Networking and Interprocess Communication</a> »</li> <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> »</li> <li class="nav-item nav-item-this"><a href="">Exceptions</a></li> <li class="right">
<div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box"> <input type="submit" value="Go"> </form> </div> | </li> <li class="right"><label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> |</li> </ul> </div>
<div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <section id="exceptions"><span id="asyncio-exceptions"></span><h1>Exceptions<a class="headerlink" href="#exceptions" title="Link to this heading">¶</a></h1><p><strong>Source code:</strong> <a class="extlink-source reference external" href="https://github.com/python/cpython/tree/main/Lib/asyncio/exceptions.py">Lib/asyncio/exceptions.py</a></p><hr class="docutils" /><dl class="py exception"><dt class="sig sig-object py" id="asyncio.TimeoutError"><em class="property"><span class="k"><span class="pre">exception</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">TimeoutError</span></span><a class="headerlink" href="#asyncio.TimeoutError" title="Link to this definition">¶</a></dt><dd><p>A deprecated alias of <code class="xref py py-exc docutils literal notranslate"><span class="pre">TimeoutError</span></code>,raised when the operation has exceeded the given deadline.</p><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.11: </span>This class was made an alias of <code class="xref py py-exc docutils literal notranslate"><span class="pre">TimeoutError</span></code>.</p></div></dd></dl>
<dl class="py exception"><dt class="sig sig-object py" id="asyncio.CancelledError"><em class="property"><span class="k"><span class="pre">exception</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">CancelledError</span></span><a class="headerlink" href="#asyncio.CancelledError" title="Link to this definition">¶</a></dt><dd><p>The operation has been cancelled.</p><p>This exception can be caught to perform custom operationswhen asyncio Tasks are cancelled. In almost all situations theexception must be re-raised.</p><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.8: </span><code class="xref py py-exc docutils literal notranslate"><span class="pre">CancelledError</span></code> is now a subclass of <a class="reference internal" href="exceptions.html#BaseException" title="BaseException"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseException</span></code></a> rather than <a class="reference internal" href="exceptions.html#Exception" title="Exception"><code class="xref py py-class docutils literal notranslate"><span class="pre">Exception</span></code></a>.</p></div></dd></dl>
<dl class="py exception"><dt class="sig sig-object py" id="asyncio.InvalidStateError"><em class="property"><span class="k"><span class="pre">exception</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">InvalidStateError</span></span><a class="headerlink" href="#asyncio.InvalidStateError" title="Link to this definition">¶</a></dt><dd><p>Invalid internal state of <a class="reference internal" href="asyncio-task.html#asyncio.Task" title="asyncio.Task"><code class="xref py py-class docutils literal notranslate"><span class="pre">Task</span></code></a> or <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>.</p><p>Can be raised in situations like setting a result value for a<em>Future</em> object that already has a result value set.</p></dd></dl>
<dl class="py exception"><dt class="sig sig-object py" id="asyncio.SendfileNotAvailableError"><em class="property"><span class="k"><span class="pre">exception</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">SendfileNotAvailableError</span></span><a class="headerlink" href="#asyncio.SendfileNotAvailableError" title="Link to this definition">¶</a></dt><dd><p>The “sendfile” syscall is not available for the givensocket or file type.</p><p>A subclass of <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>.</p></dd></dl>
<dl class="py exception"><dt class="sig sig-object py" id="asyncio.IncompleteReadError"><em class="property"><span class="k"><span class="pre">exception</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">IncompleteReadError</span></span><a class="headerlink" href="#asyncio.IncompleteReadError" title="Link to this definition">¶</a></dt><dd><p>The requested read operation did not complete fully.</p><p>Raised by the <a class="reference internal" href="asyncio-stream.html#asyncio-streams"><span class="std std-ref">asyncio stream APIs</span></a>.</p><p>This exception is a subclass of <a class="reference internal" href="exceptions.html#EOFError" title="EOFError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">EOFError</span></code></a>.</p><dl class="py attribute"><dt class="sig sig-object py" id="asyncio.IncompleteReadError.expected"><span class="sig-name descname"><span class="pre">expected</span></span><a class="headerlink" href="#asyncio.IncompleteReadError.expected" title="Link to this definition">¶</a></dt><dd><p>The total number (<a class="reference internal" href="functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a>) of expected bytes.</p></dd></dl>
<dl class="py attribute"><dt class="sig sig-object py" id="asyncio.IncompleteReadError.partial"><span class="sig-name descname"><span class="pre">partial</span></span><a class="headerlink" href="#asyncio.IncompleteReadError.partial" title="Link to this definition">¶</a></dt><dd><p>A string of <a class="reference internal" href="stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> read before the end of stream was reached.</p></dd></dl>
</dd></dl>
<dl class="py exception"><dt class="sig sig-object py" id="asyncio.LimitOverrunError"><em class="property"><span class="k"><span class="pre">exception</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">LimitOverrunError</span></span><a class="headerlink" href="#asyncio.LimitOverrunError" title="Link to this definition">¶</a></dt><dd><p>Reached the buffer size limit while looking for a separator.</p><p>Raised by the <a class="reference internal" href="asyncio-stream.html#asyncio-streams"><span class="std std-ref">asyncio stream APIs</span></a>.</p><dl class="py attribute"><dt class="sig sig-object py" id="asyncio.LimitOverrunError.consumed"><span class="sig-name descname"><span class="pre">consumed</span></span><a class="headerlink" href="#asyncio.LimitOverrunError.consumed" title="Link to this definition">¶</a></dt><dd><p>The total number of to be consumed bytes.</p></dd></dl>
</dd></dl>
</section>
<div class="clearer"></div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="Main"> <div class="sphinxsidebarwrapper"> <div> <h4>Previous topic</h4> <p class="topless"><a href="asyncio-queue.html" title="previous chapter">Queues</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="asyncio-graph.html" title="next chapter">Call Graph Introspection</a></p> </div> <script> document.addEventListener('DOMContentLoaded', () => { const title = document.querySelector('meta[property="og:title"]').content; const elements = document.querySelectorAll('.improvepage'); const pageurl = window.location.href.split('?')[0]; elements.forEach(element => { const url = new URL(element.href.split('?')[0].replace("-nojs", "")); url.searchParams.set('pagetitle', title); url.searchParams.set('pageurl', pageurl); url.searchParams.set('pagesource', "library/asyncio-exceptions.rst"); element.href = url.toString(); }); }); </script> <div role="note" aria-label="source link"> <h3>This page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a bug</a></li> <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li> <li> <a href="https://github.com/python/cpython/blob/main/Doc/library/asyncio-exceptions.rst?plain=1" rel="nofollow">Show source </a> </li> </ul> </div> </div><div id="sidebarbutton" title="Collapse sidebar"><span>«</span></div>
</div> <div class="clearer"></div> </div> <div class="related" role="navigation" aria-label="Related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="asyncio-graph.html" title="Call Graph Introspection" >next</a> |</li> <li class="right" > <a href="asyncio-queue.html" title="Queues" >previous</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.15.0a6 Documentation</a> » </li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="ipc.html" >Networking and Interprocess Communication</a> »</li> <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> »</li> <li class="nav-item nav-item-this"><a href="">Exceptions</a></li> <li class="right">
<div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box"> <input type="submit" value="Go"> </form> </div> | </li> <li class="right"><label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> |</li> </ul> </div> <div class="footer"> © <a href="../copyright.html">Copyright</a> 2001 Python Software Foundation. <br> This page is licensed under the Python Software Foundation License Version 2. <br> Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. <br> See <a href="/license.html">History and License</a> for more information.<br> <br>
The Python Software Foundation is a non-profit corporation.<a href="https://www.python.org/psf/donations/">Please donate.</a><br> <br> Last updated on Mar 10, 2026 (08:58 UTC). <a href="/bugs.html">Found a bug</a>? <br>
Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3. </div>
</body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454<!DOCTYPE html>
<html lang="en" data-content_root="../"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta property="og:title" content="Extending" /><meta property="og:type" content="website" /><meta property="og:url" content="https://docs.python.org/3/library/asyncio-extending.html" /><meta property="og:site_name" content="Python documentation" /><meta property="og:description" content="The main direction for asyncio extending is writing custom event loop classes. Asyncio has helpers that could be used to simplify this task. Writing a Custom Event Loop: asyncio.AbstractEventLoop d..." /><meta property="og:image:width" content="1146" /><meta property="og:image:height" content="600" /><meta property="og:image" content="https://docs.python.org/3.15/_images/social_previews/summary_library_asyncio-extending_1cf80ba1.png" /><meta property="og:image:alt" content="The main direction for asyncio extending is writing custom event loop classes. Asyncio has helpers that could be used to simplify this task. Writing a Custom Event Loop: asyncio.AbstractEventLoop d..." /><meta name="description" content="The main direction for asyncio extending is writing custom event loop classes. Asyncio has helpers that could be used to simplify this task. Writing a Custom Event Loop: asyncio.AbstractEventLoop d..." /><meta name="twitter:card" content="summary_large_image" /><meta name="theme-color" content="#3776ab">
<title>Extending — Python 3.15.0a6 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" /> <link rel="stylesheet" type="text/css" href="../_static/classic.css?v=234b1a7c" /> <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=89a2f22a" /> <link rel="stylesheet" type="text/css" href="../_static/profiling-sampling-visualization.css?v=0c2600ae" /> <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" /> <script src="../_static/documentation_options.js?v=6b7c9ff5"></script> <script src="../_static/doctools.js?v=9bcbadda"></script> <script src="../_static/sphinx_highlight.js?v=dc90522c"></script> <script src="../_static/profiling-sampling-visualization.js?v=9811ed04"></script> <script src="../_static/sidebar.js"></script> <link rel="search" type="application/opensearchdescription+xml" title="Search within Python 3.15.0a6 documentation" href="../_static/opensearch.xml"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="copyright" title="Copyright" href="../copyright.html" /> <link rel="next" title="High-level API Index" href="asyncio-api-index.html" /> <link rel="prev" title="Platform Support" href="asyncio-platforms.html" /> <script defer file-types="bz2,epub,zip" data-domain="docs.python.org" src="https://analytics.python.org/js/script.file-downloads.outbound-links.js"></script> <link rel="canonical" href="https://docs.python.org/3/library/asyncio-extending.html">
<style> @media only screen { table.full-width-table { width: 100%; } } </style><link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css"> <link rel="shortcut icon" type="image/png" href="../_static/py.svg"> <script type="text/javascript" src="../_static/copybutton.js"></script> <script type="text/javascript" src="../_static/menu.js"></script> <script type="text/javascript" src="../_static/search-focus.js"></script> <script type="text/javascript" src="../_static/themetoggle.js"></script> <script type="text/javascript" src="../_static/rtd_switcher.js"></script> <meta name="readthedocs-addons-api-version" content="1">
</head><body><div class="mobile-nav"> <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation" aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu"> <nav class="nav-content" role="navigation"> <label for="menuToggler" class="toggler__label"> <span></span> </label> <span class="nav-items-wrapper"> <a href="https://www.python.org/" class="nav-logo"> <img src="../_static/py.svg" alt="Python logo"> </a> <span class="version_switcher_placeholder"></span> <form role="search" class="search" action="../search.html" method="get"> <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon"> <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> </svg> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q"> <input type="submit" value="Go"> </form> </span> </nav> <div class="menu-wrapper"> <nav class="menu" role="navigation" aria-label="main navigation"> <div class="language_switcher_placeholder"></div> <label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> <div> <h3><a href="../contents.html">Table of Contents</a></h3> <ul><li><a class="reference internal" href="#">Extending</a><ul><li><a class="reference internal" href="#writing-a-custom-event-loop">Writing a Custom Event Loop</a></li><li><a class="reference internal" href="#future-and-task-private-constructors">Future and Task private constructors</a></li><li><a class="reference internal" href="#task-lifetime-support">Task lifetime support</a></li></ul></li></ul>
</div> <div> <h4>Previous topic</h4> <p class="topless"><a href="asyncio-platforms.html" title="previous chapter">Platform Support</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="asyncio-api-index.html" title="next chapter">High-level API Index</a></p> </div> <script> document.addEventListener('DOMContentLoaded', () => { const title = document.querySelector('meta[property="og:title"]').content; const elements = document.querySelectorAll('.improvepage'); const pageurl = window.location.href.split('?')[0]; elements.forEach(element => { const url = new URL(element.href.split('?')[0].replace("-nojs", "")); url.searchParams.set('pagetitle', title); url.searchParams.set('pageurl', pageurl); url.searchParams.set('pagesource', "library/asyncio-extending.rst"); element.href = url.toString(); }); }); </script> <div role="note" aria-label="source link"> <h3>This page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a bug</a></li> <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li> <li> <a href="https://github.com/python/cpython/blob/main/Doc/library/asyncio-extending.rst?plain=1" rel="nofollow">Show source </a> </li> </ul> </div> </nav> </div></div>
<div class="related" role="navigation" aria-label="Related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="asyncio-api-index.html" title="High-level API Index" accesskey="N">next</a> |</li> <li class="right" > <a href="asyncio-platforms.html" title="Platform Support" accesskey="P">previous</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.15.0a6 Documentation</a> » </li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="ipc.html" >Networking and Interprocess Communication</a> »</li> <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> »</li> <li class="nav-item nav-item-this"><a href="">Extending</a></li> <li class="right">
<div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box"> <input type="submit" value="Go"> </form> </div> | </li> <li class="right"><label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> |</li> </ul> </div>
<div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <section id="extending"><h1>Extending<a class="headerlink" href="#extending" title="Link to this heading">¶</a></h1><p>The main direction for <a class="reference internal" href="asyncio.html#module-asyncio" title="asyncio: Asynchronous I/O."><code class="xref py py-mod docutils literal notranslate"><span class="pre">asyncio</span></code></a> extending is writing custom <em>event loop</em>classes. Asyncio has helpers that could be used to simplify this task.</p><div class="admonition note"><p class="admonition-title">Note</p><p>Third-parties should reuse existing asyncio code with caution,a new Python version is free to break backward compatibilityin <em>internal</em> part of API.</p></div><section id="writing-a-custom-event-loop"><h2>Writing a Custom Event Loop<a class="headerlink" href="#writing-a-custom-event-loop" title="Link to this heading">¶</a></h2><p><a class="reference internal" href="asyncio-eventloop.html#asyncio.AbstractEventLoop" title="asyncio.AbstractEventLoop"><code class="xref py py-class docutils literal notranslate"><span class="pre">asyncio.AbstractEventLoop</span></code></a> declares very many methods. Implementing all themfrom scratch is a tedious job.</p><p>A loop can get many common methods implementation for free by inheriting from<code class="xref py py-class docutils literal notranslate"><span class="pre">asyncio.BaseEventLoop</span></code>.</p><p>In turn, the successor should implement a bunch of <em>private</em> methods declared but notimplemented in <code class="xref py py-class docutils literal notranslate"><span class="pre">asyncio.BaseEventLoop</span></code>.</p><p>For example, <code class="docutils literal notranslate"><span class="pre">loop.create_connection()</span></code> checks arguments, resolves DNS addresses, andcalls <code class="docutils literal notranslate"><span class="pre">loop._make_socket_transport()</span></code> that should be implemented by inherited class.The <code class="docutils literal notranslate"><span class="pre">_make_socket_transport()</span></code> method is not documented and is considered as an<em>internal</em> API.</p></section><section id="future-and-task-private-constructors"><h2>Future and Task private constructors<a class="headerlink" href="#future-and-task-private-constructors" title="Link to this heading">¶</a></h2><p><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">asyncio.Future</span></code></a> and <a class="reference internal" href="asyncio-task.html#asyncio.Task" title="asyncio.Task"><code class="xref py py-class docutils literal notranslate"><span class="pre">asyncio.Task</span></code></a> should be never created directly,please use corresponding <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.create_future" title="asyncio.loop.create_future"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.create_future()</span></code></a> and <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 <a class="reference internal" href="asyncio-task.html#asyncio.create_task" title="asyncio.create_task"><code class="xref py py-func docutils literal notranslate"><span class="pre">asyncio.create_task()</span></code></a> factories instead.</p><p>However, third-party <em>event loops</em> may <em>reuse</em> built-in future and task implementationsfor the sake of getting a complex and highly optimized code for free.</p><p>For this purpose the following, <em>private</em> constructors are listed:</p><dl class="py method"><dt class="sig sig-object py" id="asyncio.Future.__init__"><span class="sig-prename descclassname"><span class="pre">Future.</span></span><span class="sig-name descname"><span class="pre">__init__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="keyword-only-separator o"><abbr title="Keyword-only parameters separator (PEP 3102)"><span class="pre">*</span></abbr></span></em>, <em class="sig-param"><span class="n"><span class="pre">loop</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future.__init__" title="Link to this definition">¶</a></dt><dd><p>Create a built-in future instance.</p><p><em>loop</em> is an optional event loop instance.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.Task.__init__"><span class="sig-prename descclassname"><span class="pre">Task.</span></span><span class="sig-name descname"><span class="pre">__init__</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="keyword-only-separator o"><abbr title="Keyword-only parameters separator (PEP 3102)"><span class="pre">*</span></abbr></span></em>, <em class="sig-param"><span class="n"><span class="pre">loop</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <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.Task.__init__" title="Link to this definition">¶</a></dt><dd><p>Create a built-in task instance.</p><p><em>loop</em> is an optional event loop instance. The rest of arguments are described in<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> description.</p><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.11: </span><em>context</em> argument is added.</p></div></dd></dl>
</section><section id="task-lifetime-support"><h2>Task lifetime support<a class="headerlink" href="#task-lifetime-support" title="Link to this heading">¶</a></h2><p>A third party task implementation should call the following functions to keep a taskvisible by <a class="reference internal" href="asyncio-task.html#asyncio.all_tasks" title="asyncio.all_tasks"><code class="xref py py-func docutils literal notranslate"><span class="pre">asyncio.all_tasks()</span></code></a> and <a class="reference internal" href="asyncio-task.html#asyncio.current_task" title="asyncio.current_task"><code class="xref py py-func docutils literal notranslate"><span class="pre">asyncio.current_task()</span></code></a>:</p><dl class="py function"><dt class="sig sig-object py" id="asyncio._register_task"><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">_register_task</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">task</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio._register_task" title="Link to this definition">¶</a></dt><dd><p>Register a new <em>task</em> as managed by <em>asyncio</em>.</p><p>Call the function from a task constructor.</p></dd></dl>
<dl class="py function"><dt class="sig sig-object py" id="asyncio._unregister_task"><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">_unregister_task</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">task</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio._unregister_task" title="Link to this definition">¶</a></dt><dd><p>Unregister a <em>task</em> from <em>asyncio</em> internal structures.</p><p>The function should be called when a task is about to finish.</p></dd></dl>
<dl class="py function"><dt class="sig sig-object py" id="asyncio._enter_task"><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">_enter_task</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">task</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio._enter_task" title="Link to this definition">¶</a></dt><dd><p>Switch the current task to the <em>task</em> argument.</p><p>Call the function just before executing a portion of embedded <em>coroutine</em>(<a class="reference internal" href="../reference/datamodel.html#coroutine.send" title="coroutine.send"><code class="xref py py-meth docutils literal notranslate"><span class="pre">coroutine.send()</span></code></a> or <a class="reference internal" href="../reference/datamodel.html#coroutine.throw" title="coroutine.throw"><code class="xref py py-meth docutils literal notranslate"><span class="pre">coroutine.throw()</span></code></a>).</p></dd></dl>
<dl class="py function"><dt class="sig sig-object py" id="asyncio._leave_task"><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">_leave_task</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">task</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio._leave_task" title="Link to this definition">¶</a></dt><dd><p>Switch the current task back from <em>task</em> to <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p><p>Call the function just after <a class="reference internal" href="../reference/datamodel.html#coroutine.send" title="coroutine.send"><code class="xref py py-meth docutils literal notranslate"><span class="pre">coroutine.send()</span></code></a> or <a class="reference internal" href="../reference/datamodel.html#coroutine.throw" title="coroutine.throw"><code class="xref py py-meth docutils literal notranslate"><span class="pre">coroutine.throw()</span></code></a>execution.</p></dd></dl>
</section></section>
<div class="clearer"></div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="Main"> <div class="sphinxsidebarwrapper"> <div> <h3><a href="../contents.html">Table of Contents</a></h3> <ul><li><a class="reference internal" href="#">Extending</a><ul><li><a class="reference internal" href="#writing-a-custom-event-loop">Writing a Custom Event Loop</a></li><li><a class="reference internal" href="#future-and-task-private-constructors">Future and Task private constructors</a></li><li><a class="reference internal" href="#task-lifetime-support">Task lifetime support</a></li></ul></li></ul>
</div> <div> <h4>Previous topic</h4> <p class="topless"><a href="asyncio-platforms.html" title="previous chapter">Platform Support</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="asyncio-api-index.html" title="next chapter">High-level API Index</a></p> </div> <script> document.addEventListener('DOMContentLoaded', () => { const title = document.querySelector('meta[property="og:title"]').content; const elements = document.querySelectorAll('.improvepage'); const pageurl = window.location.href.split('?')[0]; elements.forEach(element => { const url = new URL(element.href.split('?')[0].replace("-nojs", "")); url.searchParams.set('pagetitle', title); url.searchParams.set('pageurl', pageurl); url.searchParams.set('pagesource', "library/asyncio-extending.rst"); element.href = url.toString(); }); }); </script> <div role="note" aria-label="source link"> <h3>This page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a bug</a></li> <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li> <li> <a href="https://github.com/python/cpython/blob/main/Doc/library/asyncio-extending.rst?plain=1" rel="nofollow">Show source </a> </li> </ul> </div> </div><div id="sidebarbutton" title="Collapse sidebar"><span>«</span></div>
</div> <div class="clearer"></div> </div> <div class="related" role="navigation" aria-label="Related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="asyncio-api-index.html" title="High-level API Index" >next</a> |</li> <li class="right" > <a href="asyncio-platforms.html" title="Platform Support" >previous</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.15.0a6 Documentation</a> » </li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="ipc.html" >Networking and Interprocess Communication</a> »</li> <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> »</li> <li class="nav-item nav-item-this"><a href="">Extending</a></li> <li class="right">
<div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box"> <input type="submit" value="Go"> </form> </div> | </li> <li class="right"><label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> |</li> </ul> </div> <div class="footer"> © <a href="../copyright.html">Copyright</a> 2001 Python Software Foundation. <br> This page is licensed under the Python Software Foundation License Version 2. <br> Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. <br> See <a href="/license.html">History and License</a> for more information.<br> <br>
The Python Software Foundation is a non-profit corporation.<a href="https://www.python.org/psf/donations/">Please donate.</a><br> <br> Last updated on Mar 10, 2026 (08:58 UTC). <a href="/bugs.html">Found a bug</a>? <br>
Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3. </div>
</body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636<!DOCTYPE html>
<html lang="en" data-content_root="../"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta property="og:title" content="Futures" /><meta property="og:type" content="website" /><meta property="og:url" content="https://docs.python.org/3/library/asyncio-future.html" /><meta property="og:site_name" content="Python documentation" /><meta property="og:description" content="Source code: Lib/asyncio/futures.py, Lib/asyncio/base_futures.py Future objects are used to bridge low-level callback-based code with high-level async/await code. Future Functions: Future Object: T..." /><meta property="og:image:width" content="1146" /><meta property="og:image:height" content="600" /><meta property="og:image" content="https://docs.python.org/3.15/_images/social_previews/summary_library_asyncio-future_bb00f916.png" /><meta property="og:image:alt" content="Source code: Lib/asyncio/futures.py, Lib/asyncio/base_futures.py Future objects are used to bridge low-level callback-based code with high-level async/await code. Future Functions: Future Object: T..." /><meta name="description" content="Source code: Lib/asyncio/futures.py, Lib/asyncio/base_futures.py Future objects are used to bridge low-level callback-based code with high-level async/await code. Future Functions: Future Object: T..." /><meta name="twitter:card" content="summary_large_image" /><meta name="theme-color" content="#3776ab">
<title>Futures — Python 3.15.0a6 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" /> <link rel="stylesheet" type="text/css" href="../_static/classic.css?v=234b1a7c" /> <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=89a2f22a" /> <link rel="stylesheet" type="text/css" href="../_static/profiling-sampling-visualization.css?v=0c2600ae" /> <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" /> <script src="../_static/documentation_options.js?v=6b7c9ff5"></script> <script src="../_static/doctools.js?v=9bcbadda"></script> <script src="../_static/sphinx_highlight.js?v=dc90522c"></script> <script src="../_static/profiling-sampling-visualization.js?v=9811ed04"></script> <script src="../_static/sidebar.js"></script> <link rel="search" type="application/opensearchdescription+xml" title="Search within Python 3.15.0a6 documentation" href="../_static/opensearch.xml"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="copyright" title="Copyright" href="../copyright.html" /> <link rel="next" title="Transports and Protocols" href="asyncio-protocol.html" /> <link rel="prev" title="Event Loop" href="asyncio-eventloop.html" /> <script defer file-types="bz2,epub,zip" data-domain="docs.python.org" src="https://analytics.python.org/js/script.file-downloads.outbound-links.js"></script> <link rel="canonical" href="https://docs.python.org/3/library/asyncio-future.html">
<style> @media only screen { table.full-width-table { width: 100%; } } </style><link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css"> <link rel="shortcut icon" type="image/png" href="../_static/py.svg"> <script type="text/javascript" src="../_static/copybutton.js"></script> <script type="text/javascript" src="../_static/menu.js"></script> <script type="text/javascript" src="../_static/search-focus.js"></script> <script type="text/javascript" src="../_static/themetoggle.js"></script> <script type="text/javascript" src="../_static/rtd_switcher.js"></script> <meta name="readthedocs-addons-api-version" content="1">
</head><body><div class="mobile-nav"> <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation" aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu"> <nav class="nav-content" role="navigation"> <label for="menuToggler" class="toggler__label"> <span></span> </label> <span class="nav-items-wrapper"> <a href="https://www.python.org/" class="nav-logo"> <img src="../_static/py.svg" alt="Python logo"> </a> <span class="version_switcher_placeholder"></span> <form role="search" class="search" action="../search.html" method="get"> <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon"> <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> </svg> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q"> <input type="submit" value="Go"> </form> </span> </nav> <div class="menu-wrapper"> <nav class="menu" role="navigation" aria-label="main navigation"> <div class="language_switcher_placeholder"></div> <label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> <div> <h3><a href="../contents.html">Table of Contents</a></h3> <ul><li><a class="reference internal" href="#">Futures</a><ul><li><a class="reference internal" href="#future-functions">Future Functions</a></li><li><a class="reference internal" href="#future-object">Future Object</a></li></ul></li></ul>
</div> <div> <h4>Previous topic</h4> <p class="topless"><a href="asyncio-eventloop.html" title="previous chapter">Event Loop</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="asyncio-protocol.html" title="next chapter">Transports and Protocols</a></p> </div> <script> document.addEventListener('DOMContentLoaded', () => { const title = document.querySelector('meta[property="og:title"]').content; const elements = document.querySelectorAll('.improvepage'); const pageurl = window.location.href.split('?')[0]; elements.forEach(element => { const url = new URL(element.href.split('?')[0].replace("-nojs", "")); url.searchParams.set('pagetitle', title); url.searchParams.set('pageurl', pageurl); url.searchParams.set('pagesource', "library/asyncio-future.rst"); element.href = url.toString(); }); }); </script> <div role="note" aria-label="source link"> <h3>This page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a bug</a></li> <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li> <li> <a href="https://github.com/python/cpython/blob/main/Doc/library/asyncio-future.rst?plain=1" rel="nofollow">Show source </a> </li> </ul> </div> </nav> </div></div>
<div class="related" role="navigation" aria-label="Related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="asyncio-protocol.html" title="Transports and Protocols" accesskey="N">next</a> |</li> <li class="right" > <a href="asyncio-eventloop.html" title="Event Loop" accesskey="P">previous</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.15.0a6 Documentation</a> » </li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="ipc.html" >Networking and Interprocess Communication</a> »</li> <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> »</li> <li class="nav-item nav-item-this"><a href="">Futures</a></li> <li class="right">
<div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box"> <input type="submit" value="Go"> </form> </div> | </li> <li class="right"><label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> |</li> </ul> </div>
<div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <section id="futures"><span id="asyncio-futures"></span><h1>Futures<a class="headerlink" href="#futures" title="Link to this heading">¶</a></h1><p><strong>Source code:</strong> <a class="extlink-source reference external" href="https://github.com/python/cpython/tree/main/Lib/asyncio/futures.py">Lib/asyncio/futures.py</a>,<a class="extlink-source reference external" href="https://github.com/python/cpython/tree/main/Lib/asyncio/base_futures.py">Lib/asyncio/base_futures.py</a></p><hr class="docutils" /><p><em>Future</em> objects are used to bridge <strong>low-level callback-based code</strong>with high-level async/await code.</p><section id="future-functions"><h2>Future Functions<a class="headerlink" href="#future-functions" title="Link to this heading">¶</a></h2><dl class="py function"><dt class="sig sig-object py" id="asyncio.isfuture"><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">isfuture</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">obj</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.isfuture" title="Link to this definition">¶</a></dt><dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if <em>obj</em> is either of:</p><ul class="simple"><li><p>an instance of <a class="reference internal" href="#asyncio.Future" title="asyncio.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">asyncio.Future</span></code></a>,</p></li><li><p>an instance of <a class="reference internal" href="asyncio-task.html#asyncio.Task" title="asyncio.Task"><code class="xref py py-class docutils literal notranslate"><span class="pre">asyncio.Task</span></code></a>,</p></li><li><p>a Future-like object with a <code class="docutils literal notranslate"><span class="pre">_asyncio_future_blocking</span></code>attribute.</p></li></ul><div class="versionadded"><p><span class="versionmodified added">Added in version 3.5.</span></p></div></dd></dl>
<dl class="py function"><dt class="sig sig-object py" id="asyncio.ensure_future"><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">ensure_future</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">obj</span></span></em>, <em class="sig-param"><span class="keyword-only-separator o"><abbr title="Keyword-only parameters separator (PEP 3102)"><span class="pre">*</span></abbr></span></em>, <em class="sig-param"><span class="n"><span class="pre">loop</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.ensure_future" title="Link to this definition">¶</a></dt><dd><p>Return:</p><ul class="simple"><li><p><em>obj</em> argument as is, if <em>obj</em> is a <a class="reference internal" href="#asyncio.Future" title="asyncio.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">Future</span></code></a>,a <a class="reference internal" href="asyncio-task.html#asyncio.Task" title="asyncio.Task"><code class="xref py py-class docutils literal notranslate"><span class="pre">Task</span></code></a>, or a Future-like object (<a class="reference internal" href="#asyncio.isfuture" title="asyncio.isfuture"><code class="xref py py-func docutils literal notranslate"><span class="pre">isfuture()</span></code></a>is used for the test.)</p></li><li><p>a <a class="reference internal" href="asyncio-task.html#asyncio.Task" title="asyncio.Task"><code class="xref py py-class docutils literal notranslate"><span class="pre">Task</span></code></a> object wrapping <em>obj</em>, if <em>obj</em> is acoroutine (<a class="reference internal" href="asyncio-task.html#asyncio.iscoroutine" title="asyncio.iscoroutine"><code class="xref py py-func docutils literal notranslate"><span class="pre">iscoroutine()</span></code></a> is used for the test);in this case the coroutine will be scheduled by<code class="docutils literal notranslate"><span class="pre">ensure_future()</span></code>.</p></li><li><p>a <a class="reference internal" href="asyncio-task.html#asyncio.Task" title="asyncio.Task"><code class="xref py py-class docutils literal notranslate"><span class="pre">Task</span></code></a> object that would await on <em>obj</em>, if <em>obj</em> is anawaitable (<a class="reference internal" href="inspect.html#inspect.isawaitable" title="inspect.isawaitable"><code class="xref py py-func docutils literal notranslate"><span class="pre">inspect.isawaitable()</span></code></a> is used for the test.)</p></li></ul><p>If <em>obj</em> is neither of the above a <a class="reference internal" href="exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> is raised.</p><div class="admonition important"><p class="admonition-title">Important</p><p>Save a reference to the result of this function, to avoida task disappearing mid-execution.</p><p>See also the <a class="reference internal" href="asyncio-task.html#asyncio.create_task" title="asyncio.create_task"><code class="xref py py-func docutils literal notranslate"><span class="pre">create_task()</span></code></a> function which is thepreferred way for creating new tasks or use <a class="reference internal" href="asyncio-task.html#asyncio.TaskGroup" title="asyncio.TaskGroup"><code class="xref py py-class docutils literal notranslate"><span class="pre">asyncio.TaskGroup</span></code></a>which keeps reference to the task internally.</p></div><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.5.1: </span>The function accepts any <a class="reference internal" href="../glossary.html#term-awaitable"><span class="xref std std-term">awaitable</span></a> object.</p></div><div class="deprecated"><p><span class="versionmodified deprecated">Deprecated since version 3.10: </span>Deprecation warning is emitted if <em>obj</em> is not a Future-like objectand <em>loop</em> is not specified and there is no running event loop.</p></div></dd></dl>
<dl class="py function"><dt class="sig sig-object py" id="asyncio.wrap_future"><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">wrap_future</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">future</span></span></em>, <em class="sig-param"><span class="keyword-only-separator o"><abbr title="Keyword-only parameters separator (PEP 3102)"><span class="pre">*</span></abbr></span></em>, <em class="sig-param"><span class="n"><span class="pre">loop</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.wrap_future" title="Link to this definition">¶</a></dt><dd><p>Wrap a <a class="reference internal" href="concurrent.futures.html#concurrent.futures.Future" title="concurrent.futures.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">concurrent.futures.Future</span></code></a> object in a<a class="reference internal" href="#asyncio.Future" title="asyncio.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">asyncio.Future</span></code></a> object.</p><div class="deprecated"><p><span class="versionmodified deprecated">Deprecated since version 3.10: </span>Deprecation warning is emitted if <em>future</em> is not a Future-like objectand <em>loop</em> is not specified and there is no running event loop.</p></div></dd></dl>
</section><section id="future-object"><span id="asyncio-future-obj"></span><h2>Future Object<a class="headerlink" href="#future-object" title="Link to this heading">¶</a></h2><dl class="py class"><dt class="sig sig-object py" id="asyncio.Future"><em class="property"><span class="k"><span class="pre">class</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">Future</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="keyword-only-separator o"><abbr title="Keyword-only parameters separator (PEP 3102)"><span class="pre">*</span></abbr></span></em>, <em class="sig-param"><span class="n"><span class="pre">loop</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future" title="Link to this definition">¶</a></dt><dd><p>A Future represents an eventual result of an asynchronousoperation. Not thread-safe.</p><p>Future is an <a class="reference internal" href="../glossary.html#term-awaitable"><span class="xref std std-term">awaitable</span></a> object. Coroutines can await onFuture objects until they either have a result or an exceptionset, or until they are cancelled. A Future can be awaited multipletimes and the result is same.</p><p>Typically Futures are used to enable low-levelcallback-based code (e.g. in protocols implemented using asyncio<a class="reference internal" href="asyncio-protocol.html#asyncio-transports-protocols"><span class="std std-ref">transports</span></a>)to interoperate with high-level async/await code.</p><p>The rule of thumb is to never expose Future objects in user-facingAPIs, and the recommended way to create a Future object is to call<a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.create_future" title="asyncio.loop.create_future"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.create_future()</span></code></a>. This way alternative event loopimplementations can inject their own optimized implementationsof a Future object.</p><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.7: </span>Added support for the <a class="reference internal" href="contextvars.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></div><div class="deprecated"><p><span class="versionmodified deprecated">Deprecated since version 3.10: </span>Deprecation warning is emitted if <em>loop</em> is not specifiedand there is no running event loop.</p></div><dl class="py method"><dt class="sig sig-object py" id="asyncio.Future.result"><span class="sig-name descname"><span class="pre">result</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future.result" title="Link to this definition">¶</a></dt><dd><p>Return the result of the Future.</p><p>If the Future is <em>done</em> and has a result set by the<a class="reference internal" href="#asyncio.Future.set_result" title="asyncio.Future.set_result"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_result()</span></code></a> method, the result value is returned.</p><p>If the Future is <em>done</em> and has an exception set by the<a class="reference internal" href="#asyncio.Future.set_exception" title="asyncio.Future.set_exception"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_exception()</span></code></a> method, this method raises the exception.</p><p>If the Future has been <em>cancelled</em>, this method raisesa <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><p>If the Future’s result isn’t yet available, this method raisesan <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></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.Future.set_result"><span class="sig-name descname"><span class="pre">set_result</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">result</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future.set_result" title="Link to this definition">¶</a></dt><dd><p>Mark the Future as <em>done</em> and set its result.</p><p>Raises an <a class="reference internal" href="asyncio-exceptions.html#asyncio.InvalidStateError" title="asyncio.InvalidStateError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">InvalidStateError</span></code></a> error if the Future isalready <em>done</em>.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.Future.set_exception"><span class="sig-name descname"><span class="pre">set_exception</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">exception</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future.set_exception" title="Link to this definition">¶</a></dt><dd><p>Mark the Future as <em>done</em> and set an exception.</p><p>Raises an <a class="reference internal" href="asyncio-exceptions.html#asyncio.InvalidStateError" title="asyncio.InvalidStateError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">InvalidStateError</span></code></a> error if the Future isalready <em>done</em>.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.Future.done"><span class="sig-name descname"><span class="pre">done</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future.done" title="Link to this definition">¶</a></dt><dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the Future is <em>done</em>.</p><p>A Future is <em>done</em> if it was <em>cancelled</em> or if it has a resultor an exception set with <a class="reference internal" href="#asyncio.Future.set_result" title="asyncio.Future.set_result"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_result()</span></code></a> or<a class="reference internal" href="#asyncio.Future.set_exception" title="asyncio.Future.set_exception"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_exception()</span></code></a> calls.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.Future.cancelled"><span class="sig-name descname"><span class="pre">cancelled</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future.cancelled" title="Link to this definition">¶</a></dt><dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the Future was <em>cancelled</em>.</p><p>The method is usually used to check if a Future is not<em>cancelled</em> before setting a result or an exception for it:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="ow">not</span> <span class="n">fut</span><span class="o">.</span><span class="n">cancelled</span><span class="p">():</span> <span class="n">fut</span><span class="o">.</span><span class="n">set_result</span><span class="p">(</span><span class="mi">42</span><span class="p">)</span></pre></div></div></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.Future.add_done_callback"><span class="sig-name descname"><span class="pre">add_done_callback</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">callback</span></span></em>, <em class="sig-param"><span class="keyword-only-separator o"><abbr title="Keyword-only parameters separator (PEP 3102)"><span class="pre">*</span></abbr></span></em>, <em class="sig-param"><span class="n"><span class="pre">context</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future.add_done_callback" title="Link to this definition">¶</a></dt><dd><p>Add a callback to be run when the Future is <em>done</em>.</p><p>The <em>callback</em> is called with the Future object as its onlyargument.</p><p>If the Future is already <em>done</em> when this method is called,the callback is scheduled with <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.call_soon" title="asyncio.loop.call_soon"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.call_soon()</span></code></a>.</p><p>An optional keyword-only <em>context</em> argument allows specifying acustom <a class="reference internal" href="contextvars.html#contextvars.Context" title="contextvars.Context"><code class="xref py py-class docutils literal notranslate"><span class="pre">contextvars.Context</span></code></a> for the <em>callback</em> to run in.The current context is used when no <em>context</em> is provided.</p><p><a class="reference internal" href="functools.html#functools.partial" title="functools.partial"><code class="xref py py-func docutils literal notranslate"><span class="pre">functools.partial()</span></code></a> can be used to pass parametersto the callback, e.g.:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># Call 'print("Future:", fut)' when "fut" is done.</span><span class="n">fut</span><span class="o">.</span><span class="n">add_done_callback</span><span class="p">(</span> <span class="n">functools</span><span class="o">.</span><span class="n">partial</span><span class="p">(</span><span class="nb">print</span><span class="p">,</span> <span class="s2">"Future:"</span><span class="p">))</span></pre></div></div><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.7: </span>The <em>context</em> keyword-only parameter was added.See <span class="target" id="index-0"></span><a class="pep reference external" href="https://peps.python.org/pep-0567/"><strong>PEP 567</strong></a> for more details.</p></div></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.Future.remove_done_callback"><span class="sig-name descname"><span class="pre">remove_done_callback</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">callback</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future.remove_done_callback" title="Link to this definition">¶</a></dt><dd><p>Remove <em>callback</em> from the callbacks list.</p><p>Returns the number of callbacks removed, which is typically 1,unless a callback was added more than once.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.Future.cancel"><span class="sig-name descname"><span class="pre">cancel</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">msg</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future.cancel" title="Link to this definition">¶</a></dt><dd><p>Cancel the Future and schedule callbacks.</p><p>If the Future is already <em>done</em> or <em>cancelled</em>, return <code class="docutils literal notranslate"><span class="pre">False</span></code>.Otherwise, change the Future’s state to <em>cancelled</em>,schedule the callbacks, and return <code class="docutils literal notranslate"><span class="pre">True</span></code>.</p><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.9: </span>Added the <em>msg</em> parameter.</p></div></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.Future.exception"><span class="sig-name descname"><span class="pre">exception</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future.exception" title="Link to this definition">¶</a></dt><dd><p>Return the exception that was set on this Future.</p><p>The exception (or <code class="docutils literal notranslate"><span class="pre">None</span></code> if no exception was set) isreturned only if the Future is <em>done</em>.</p><p>If the Future has been <em>cancelled</em>, this method raises a<a class="reference internal" href="asyncio-exceptions.html#asyncio.CancelledError" title="asyncio.CancelledError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">CancelledError</span></code></a> exception.</p><p>If the Future isn’t <em>done</em> yet, this method raises an<a class="reference internal" href="asyncio-exceptions.html#asyncio.InvalidStateError" title="asyncio.InvalidStateError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">InvalidStateError</span></code></a> exception.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.Future.get_loop"><span class="sig-name descname"><span class="pre">get_loop</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future.get_loop" title="Link to this definition">¶</a></dt><dd><p>Return the event loop the Future object is bound to.</p><div class="versionadded"><p><span class="versionmodified added">Added in version 3.7.</span></p></div></dd></dl>
</dd></dl>
<p id="asyncio-example-future">This example creates a Future object, creates and schedules anasynchronous Task to set result for the Future, and waits untilthe Future has a result:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">set_after</span><span class="p">(</span><span class="n">fut</span><span class="p">,</span> <span class="n">delay</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span> <span class="c1"># Sleep for *delay* seconds.</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="n">delay</span><span class="p">)</span>
<span class="c1"># Set *value* as a result of *fut* Future.</span> <span class="n">fut</span><span class="o">.</span><span class="n">set_result</span><span class="p">(</span><span class="n">value</span><span class="p">)</span>
<span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">main</span><span class="p">():</span> <span class="c1"># Get the current event loop.</span> <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>
<span class="c1"># Create a new Future object.</span> <span class="n">fut</span> <span class="o">=</span> <span class="n">loop</span><span class="o">.</span><span class="n">create_future</span><span class="p">()</span>
<span class="c1"># Run "set_after()" coroutine in a parallel Task.</span> <span class="c1"># We are using the low-level "loop.create_task()" API here because</span> <span class="c1"># we already have a reference to the event loop at hand.</span> <span class="c1"># Otherwise we could have just used "asyncio.create_task()".</span> <span class="n">loop</span><span class="o">.</span><span class="n">create_task</span><span class="p">(</span> <span class="n">set_after</span><span class="p">(</span><span class="n">fut</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="s1">'... world'</span><span class="p">))</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">'hello ...'</span><span class="p">)</span>
<span class="c1"># Wait until *fut* has a result (1 second) and print it.</span> <span class="nb">print</span><span class="p">(</span><span class="k">await</span> <span class="n">fut</span><span class="p">)</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></pre></div></div><div class="admonition important"><p class="admonition-title">Important</p><p>The Future object was designed to mimic<a class="reference internal" href="concurrent.futures.html#concurrent.futures.Future" title="concurrent.futures.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">concurrent.futures.Future</span></code></a>. Key differences include:</p><ul class="simple"><li><p>unlike asyncio Futures, <a class="reference internal" href="concurrent.futures.html#concurrent.futures.Future" title="concurrent.futures.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">concurrent.futures.Future</span></code></a>instances cannot be awaited.</p></li><li><p><a class="reference internal" href="#asyncio.Future.result" title="asyncio.Future.result"><code class="xref py py-meth docutils literal notranslate"><span class="pre">asyncio.Future.result()</span></code></a> and <a class="reference internal" href="#asyncio.Future.exception" title="asyncio.Future.exception"><code class="xref py py-meth docutils literal notranslate"><span class="pre">asyncio.Future.exception()</span></code></a>do not accept the <em>timeout</em> argument.</p></li><li><p><a class="reference internal" href="#asyncio.Future.result" title="asyncio.Future.result"><code class="xref py py-meth docutils literal notranslate"><span class="pre">asyncio.Future.result()</span></code></a> and <a class="reference internal" href="#asyncio.Future.exception" title="asyncio.Future.exception"><code class="xref py py-meth docutils literal notranslate"><span class="pre">asyncio.Future.exception()</span></code></a>raise an <a class="reference internal" href="asyncio-exceptions.html#asyncio.InvalidStateError" title="asyncio.InvalidStateError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">InvalidStateError</span></code></a> exception when the Future is not<em>done</em>.</p></li><li><p>Callbacks registered with <a class="reference internal" href="#asyncio.Future.add_done_callback" title="asyncio.Future.add_done_callback"><code class="xref py py-meth docutils literal notranslate"><span class="pre">asyncio.Future.add_done_callback()</span></code></a>are not called immediately. They are scheduled with<a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.call_soon" title="asyncio.loop.call_soon"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.call_soon()</span></code></a> instead.</p></li><li><p>asyncio Future is not compatible with the<a class="reference internal" href="concurrent.futures.html#concurrent.futures.wait" title="concurrent.futures.wait"><code class="xref py py-func docutils literal notranslate"><span class="pre">concurrent.futures.wait()</span></code></a> and<a class="reference internal" href="concurrent.futures.html#concurrent.futures.as_completed" title="concurrent.futures.as_completed"><code class="xref py py-func docutils literal notranslate"><span class="pre">concurrent.futures.as_completed()</span></code></a> functions.</p></li><li><p><a class="reference internal" href="#asyncio.Future.cancel" title="asyncio.Future.cancel"><code class="xref py py-meth docutils literal notranslate"><span class="pre">asyncio.Future.cancel()</span></code></a> accepts an optional <code class="docutils literal notranslate"><span class="pre">msg</span></code> argument,but <a class="reference internal" href="concurrent.futures.html#concurrent.futures.Future.cancel" title="concurrent.futures.Future.cancel"><code class="xref py py-meth docutils literal notranslate"><span class="pre">concurrent.futures.Future.cancel()</span></code></a> does not.</p></li></ul></div></section></section>
<div class="clearer"></div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="Main"> <div class="sphinxsidebarwrapper"> <div> <h3><a href="../contents.html">Table of Contents</a></h3> <ul><li><a class="reference internal" href="#">Futures</a><ul><li><a class="reference internal" href="#future-functions">Future Functions</a></li><li><a class="reference internal" href="#future-object">Future Object</a></li></ul></li></ul>
</div> <div> <h4>Previous topic</h4> <p class="topless"><a href="asyncio-eventloop.html" title="previous chapter">Event Loop</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="asyncio-protocol.html" title="next chapter">Transports and Protocols</a></p> </div> <script> document.addEventListener('DOMContentLoaded', () => { const title = document.querySelector('meta[property="og:title"]').content; const elements = document.querySelectorAll('.improvepage'); const pageurl = window.location.href.split('?')[0]; elements.forEach(element => { const url = new URL(element.href.split('?')[0].replace("-nojs", "")); url.searchParams.set('pagetitle', title); url.searchParams.set('pageurl', pageurl); url.searchParams.set('pagesource', "library/asyncio-future.rst"); element.href = url.toString(); }); }); </script> <div role="note" aria-label="source link"> <h3>This page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a bug</a></li> <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li> <li> <a href="https://github.com/python/cpython/blob/main/Doc/library/asyncio-future.rst?plain=1" rel="nofollow">Show source </a> </li> </ul> </div> </div><div id="sidebarbutton" title="Collapse sidebar"><span>«</span></div>
</div> <div class="clearer"></div> </div> <div class="related" role="navigation" aria-label="Related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="asyncio-protocol.html" title="Transports and Protocols" >next</a> |</li> <li class="right" > <a href="asyncio-eventloop.html" title="Event Loop" >previous</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.15.0a6 Documentation</a> » </li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="ipc.html" >Networking and Interprocess Communication</a> »</li> <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> »</li> <li class="nav-item nav-item-this"><a href="">Futures</a></li> <li class="right">
<div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box"> <input type="submit" value="Go"> </form> </div> | </li> <li class="right"><label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> |</li> </ul> </div> <div class="footer"> © <a href="../copyright.html">Copyright</a> 2001 Python Software Foundation. <br> This page is licensed under the Python Software Foundation License Version 2. <br> Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. <br> See <a href="/license.html">History and License</a> for more information.<br> <br>
The Python Software Foundation is a non-profit corporation.<a href="https://www.python.org/psf/donations/">Please donate.</a><br> <br> Last updated on Mar 10, 2026 (08:58 UTC). <a href="/bugs.html">Found a bug</a>? <br>
Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3. </div>
</body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494<!DOCTYPE html>
<html lang="en" data-content_root="../"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta property="og:title" content="Call Graph Introspection" /><meta property="og:type" content="website" /><meta property="og:url" content="https://docs.python.org/3/library/asyncio-graph.html" /><meta property="og:site_name" content="Python documentation" /><meta property="og:description" content="Source code: Lib/asyncio/graph.py asyncio has powerful runtime call graph introspection utilities to trace the entire call graph of a running coroutine or task, or a suspended future. These utiliti..." /><meta property="og:image:width" content="1146" /><meta property="og:image:height" content="600" /><meta property="og:image" content="https://docs.python.org/3.15/_images/social_previews/summary_library_asyncio-graph_240d61f9.png" /><meta property="og:image:alt" content="Source code: Lib/asyncio/graph.py asyncio has powerful runtime call graph introspection utilities to trace the entire call graph of a running coroutine or task, or a suspended future. These utiliti..." /><meta name="description" content="Source code: Lib/asyncio/graph.py asyncio has powerful runtime call graph introspection utilities to trace the entire call graph of a running coroutine or task, or a suspended future. These utiliti..." /><meta name="twitter:card" content="summary_large_image" /><meta name="theme-color" content="#3776ab">
<title>Call Graph Introspection — Python 3.15.0a6 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" /> <link rel="stylesheet" type="text/css" href="../_static/classic.css?v=234b1a7c" /> <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=89a2f22a" /> <link rel="stylesheet" type="text/css" href="../_static/profiling-sampling-visualization.css?v=0c2600ae" /> <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" /> <script src="../_static/documentation_options.js?v=6b7c9ff5"></script> <script src="../_static/doctools.js?v=9bcbadda"></script> <script src="../_static/sphinx_highlight.js?v=dc90522c"></script> <script src="../_static/profiling-sampling-visualization.js?v=9811ed04"></script> <script src="../_static/sidebar.js"></script> <link rel="search" type="application/opensearchdescription+xml" title="Search within Python 3.15.0a6 documentation" href="../_static/opensearch.xml"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="copyright" title="Copyright" href="../copyright.html" /> <link rel="next" title="Event Loop" href="asyncio-eventloop.html" /> <link rel="prev" title="Exceptions" href="asyncio-exceptions.html" /> <script defer file-types="bz2,epub,zip" data-domain="docs.python.org" src="https://analytics.python.org/js/script.file-downloads.outbound-links.js"></script> <link rel="canonical" href="https://docs.python.org/3/library/asyncio-graph.html">
<style> @media only screen { table.full-width-table { width: 100%; } } </style><link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css"> <link rel="shortcut icon" type="image/png" href="../_static/py.svg"> <script type="text/javascript" src="../_static/copybutton.js"></script> <script type="text/javascript" src="../_static/menu.js"></script> <script type="text/javascript" src="../_static/search-focus.js"></script> <script type="text/javascript" src="../_static/themetoggle.js"></script> <script type="text/javascript" src="../_static/rtd_switcher.js"></script> <meta name="readthedocs-addons-api-version" content="1">
</head><body><div class="mobile-nav"> <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation" aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu"> <nav class="nav-content" role="navigation"> <label for="menuToggler" class="toggler__label"> <span></span> </label> <span class="nav-items-wrapper"> <a href="https://www.python.org/" class="nav-logo"> <img src="../_static/py.svg" alt="Python logo"> </a> <span class="version_switcher_placeholder"></span> <form role="search" class="search" action="../search.html" method="get"> <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon"> <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> </svg> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q"> <input type="submit" value="Go"> </form> </span> </nav> <div class="menu-wrapper"> <nav class="menu" role="navigation" aria-label="main navigation"> <div class="language_switcher_placeholder"></div> <label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> <div> <h3><a href="../contents.html">Table of Contents</a></h3> <ul><li><a class="reference internal" href="#">Call Graph Introspection</a><ul><li><a class="reference internal" href="#low-level-utility-functions">Low level utility functions</a></li></ul></li></ul>
</div> <div> <h4>Previous topic</h4> <p class="topless"><a href="asyncio-exceptions.html" title="previous chapter">Exceptions</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="asyncio-eventloop.html" title="next chapter">Event Loop</a></p> </div> <script> document.addEventListener('DOMContentLoaded', () => { const title = document.querySelector('meta[property="og:title"]').content; const elements = document.querySelectorAll('.improvepage'); const pageurl = window.location.href.split('?')[0]; elements.forEach(element => { const url = new URL(element.href.split('?')[0].replace("-nojs", "")); url.searchParams.set('pagetitle', title); url.searchParams.set('pageurl', pageurl); url.searchParams.set('pagesource', "library/asyncio-graph.rst"); element.href = url.toString(); }); }); </script> <div role="note" aria-label="source link"> <h3>This page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a bug</a></li> <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li> <li> <a href="https://github.com/python/cpython/blob/main/Doc/library/asyncio-graph.rst?plain=1" rel="nofollow">Show source </a> </li> </ul> </div> </nav> </div></div>
<div class="related" role="navigation" aria-label="Related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="asyncio-eventloop.html" title="Event Loop" accesskey="N">next</a> |</li> <li class="right" > <a href="asyncio-exceptions.html" title="Exceptions" accesskey="P">previous</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.15.0a6 Documentation</a> » </li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="ipc.html" >Networking and Interprocess Communication</a> »</li> <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> »</li> <li class="nav-item nav-item-this"><a href="">Call Graph Introspection</a></li> <li class="right">
<div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box"> <input type="submit" value="Go"> </form> </div> | </li> <li class="right"><label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> |</li> </ul> </div>
<div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <section id="call-graph-introspection"><span id="asyncio-graph"></span><h1>Call Graph Introspection<a class="headerlink" href="#call-graph-introspection" title="Link to this heading">¶</a></h1><p><strong>Source code:</strong> <a class="extlink-source reference external" href="https://github.com/python/cpython/tree/main/Lib/asyncio/graph.py">Lib/asyncio/graph.py</a></p><hr class="docutils" /><p>asyncio has powerful runtime call graph introspection utilitiesto trace the entire call graph of a running <em>coroutine</em> or <em>task</em>, ora suspended <em>future</em>. These utilities and the underlying machinerycan be used from within a Python program or by external profilersand debuggers.</p><div class="versionadded"><p><span class="versionmodified added">Added in version 3.14.</span></p></div><dl class="py function"><dt class="sig sig-object py" id="asyncio.print_call_graph"><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">print_call_graph</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">future</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="positional-only-separator o"><abbr title="Positional-only parameter separator (PEP 570)"><span class="pre">/</span></abbr></span></em>, <em class="sig-param"><span class="keyword-only-separator o"><abbr title="Keyword-only parameters separator (PEP 3102)"><span class="pre">*</span></abbr></span></em>, <em class="sig-param"><span class="n"><span class="pre">file</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">depth</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">1</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.print_call_graph" title="Link to this definition">¶</a></dt><dd><p>Print the async call graph for the current task or the provided<a class="reference internal" href="asyncio-task.html#asyncio.Task" title="asyncio.Task"><code class="xref py py-class docutils literal notranslate"><span class="pre">Task</span></code></a> or <a 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>.</p><p>This function prints entries starting from the top frame and goingdown towards the invocation point.</p><p>The function receives an optional <em>future</em> argument.If not passed, the current running task will be used.</p><p>If the function is called on <em>the current task</em>, the optionalkeyword-only <em>depth</em> argument can be used to skip the specifiednumber of frames from top of the stack.</p><p>If the optional keyword-only <em>limit</em> argument is provided, each call stackin the resulting graph is truncated to include at most <code class="docutils literal notranslate"><span class="pre">abs(limit)</span></code>entries. If <em>limit</em> is positive, the entries left are the closest tothe invocation point. If <em>limit</em> is negative, the topmost entries areleft. If <em>limit</em> is omitted or <code class="docutils literal notranslate"><span class="pre">None</span></code>, all entries are present.If <em>limit</em> is <code class="docutils literal notranslate"><span class="pre">0</span></code>, the call stack is not printed at all, only“awaited by” information is printed.</p><p>If <em>file</em> is omitted or <code class="docutils literal notranslate"><span class="pre">None</span></code>, the function will printto <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><p><strong>Example:</strong></p><p>The following Python code:</p><div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span><span class="w"> </span><span class="nn">asyncio</span>
<span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">test</span><span class="p">():</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">print_call_graph</span><span class="p">()</span>
<span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">main</span><span class="p">():</span> <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">g</span><span class="p">:</span> <span class="n">g</span><span class="o">.</span><span class="n">create_task</span><span class="p">(</span><span class="n">test</span><span class="p">(),</span> <span class="n">name</span><span class="o">=</span><span class="s1">'test'</span><span class="p">)</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></pre></div></div><p>will print:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="o">*</span> <span class="n">Task</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">'test'</span><span class="p">,</span> <span class="nb">id</span><span class="o">=</span><span class="mh">0x1039f0fe0</span><span class="p">)</span><span class="o">+</span> <span class="n">Call</span> <span class="n">stack</span><span class="p">:</span><span class="o">|</span> <span class="n">File</span> <span class="s1">'t2.py'</span><span class="p">,</span> <span class="n">line</span> <span class="mi">4</span><span class="p">,</span> <span class="ow">in</span> <span class="k">async</span> <span class="n">test</span><span class="p">()</span><span class="o">+</span> <span class="n">Awaited</span> <span class="n">by</span><span class="p">:</span> <span class="o">*</span> <span class="n">Task</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">'Task-1'</span><span class="p">,</span> <span class="nb">id</span><span class="o">=</span><span class="mh">0x103a5e060</span><span class="p">)</span> <span class="o">+</span> <span class="n">Call</span> <span class="n">stack</span><span class="p">:</span> <span class="o">|</span> <span class="n">File</span> <span class="s1">'taskgroups.py'</span><span class="p">,</span> <span class="n">line</span> <span class="mi">107</span><span class="p">,</span> <span class="ow">in</span> <span class="k">async</span> <span class="n">TaskGroup</span><span class="o">.</span><span class="fm">__aexit__</span><span class="p">()</span> <span class="o">|</span> <span class="n">File</span> <span class="s1">'t2.py'</span><span class="p">,</span> <span class="n">line</span> <span class="mi">7</span><span class="p">,</span> <span class="ow">in</span> <span class="k">async</span> <span class="n">main</span><span class="p">()</span></pre></div></div></dd></dl>
<dl class="py function"><dt class="sig sig-object py" id="asyncio.format_call_graph"><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">format_call_graph</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">future</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="positional-only-separator o"><abbr title="Positional-only parameter separator (PEP 570)"><span class="pre">/</span></abbr></span></em>, <em class="sig-param"><span class="keyword-only-separator o"><abbr title="Keyword-only parameters separator (PEP 3102)"><span class="pre">*</span></abbr></span></em>, <em class="sig-param"><span class="n"><span class="pre">depth</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">1</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.format_call_graph" title="Link to this definition">¶</a></dt><dd><p>Like <a class="reference internal" href="#asyncio.print_call_graph" title="asyncio.print_call_graph"><code class="xref py py-func docutils literal notranslate"><span class="pre">print_call_graph()</span></code></a>, but returns a string.If <em>future</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code> and there’s no current task,the function returns an empty string.</p></dd></dl>
<dl class="py function"><dt class="sig sig-object py" id="asyncio.capture_call_graph"><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">capture_call_graph</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">future</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="positional-only-separator o"><abbr title="Positional-only parameter separator (PEP 570)"><span class="pre">/</span></abbr></span></em>, <em class="sig-param"><span class="keyword-only-separator o"><abbr title="Keyword-only parameters separator (PEP 3102)"><span class="pre">*</span></abbr></span></em>, <em class="sig-param"><span class="n"><span class="pre">depth</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">1</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.capture_call_graph" title="Link to this definition">¶</a></dt><dd><p>Capture the async call graph for the current task or the provided<a class="reference internal" href="asyncio-task.html#asyncio.Task" title="asyncio.Task"><code class="xref py py-class docutils literal notranslate"><span class="pre">Task</span></code></a> or <a 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>.</p><p>The function receives an optional <em>future</em> argument.If not passed, the current running task will be used. If there’s nocurrent task, the function returns <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p><p>If the function is called on <em>the current task</em>, the optionalkeyword-only <em>depth</em> argument can be used to skip the specifiednumber of frames from top of the stack.</p><p>Returns a <code class="docutils literal notranslate"><span class="pre">FutureCallGraph</span></code> data class object:</p><ul><li><p><code class="docutils literal notranslate"><span class="pre">FutureCallGraph(future,</span> <span class="pre">call_stack,</span> <span class="pre">awaited_by)</span></code></p><blockquote><div><p>Where <em>future</em> is a reference to 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> ora <a class="reference internal" href="asyncio-task.html#asyncio.Task" title="asyncio.Task"><code class="xref py py-class docutils literal notranslate"><span class="pre">Task</span></code></a> (or their subclasses.)</p><p><code class="docutils literal notranslate"><span class="pre">call_stack</span></code> is a tuple of <code class="docutils literal notranslate"><span class="pre">FrameCallGraphEntry</span></code> objects.</p><p><code class="docutils literal notranslate"><span class="pre">awaited_by</span></code> is a tuple of <code class="docutils literal notranslate"><span class="pre">FutureCallGraph</span></code> objects.</p></div></blockquote></li><li><p><code class="docutils literal notranslate"><span class="pre">FrameCallGraphEntry(frame)</span></code></p><blockquote><div><p>Where <em>frame</em> is a frame object of a regular Python functionin the call stack.</p></div></blockquote></li></ul></dd></dl>
<section id="low-level-utility-functions"><h2>Low level utility functions<a class="headerlink" href="#low-level-utility-functions" title="Link to this heading">¶</a></h2><p>To introspect an async call graph asyncio requires cooperation fromcontrol flow structures, such as <a class="reference internal" href="asyncio-task.html#asyncio.shield" title="asyncio.shield"><code class="xref py py-func docutils literal notranslate"><span class="pre">shield()</span></code></a> or <a class="reference internal" href="asyncio-task.html#asyncio.TaskGroup" title="asyncio.TaskGroup"><code class="xref py py-class docutils literal notranslate"><span class="pre">TaskGroup</span></code></a>.Any time an intermediate <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> object with low-level APIs like<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> isinvolved, the following two functions should be used to inform asyncioabout how exactly such intermediate future objects are connected withthe tasks they wrap or control.</p><dl class="py function"><dt class="sig sig-object py" id="asyncio.future_add_to_awaited_by"><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">future_add_to_awaited_by</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">future</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">waiter</span></span></em>, <em class="sig-param"><span class="positional-only-separator o"><abbr title="Positional-only parameter separator (PEP 570)"><span class="pre">/</span></abbr></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.future_add_to_awaited_by" title="Link to this definition">¶</a></dt><dd><p>Record that <em>future</em> is awaited on by <em>waiter</em>.</p><p>Both <em>future</em> and <em>waiter</em> must be instances of<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> or <a class="reference internal" href="asyncio-task.html#asyncio.Task" title="asyncio.Task"><code class="xref py py-class docutils literal notranslate"><span class="pre">Task</span></code></a> or their subclasses,otherwise the call would have no effect.</p><p>A call to <code class="docutils literal notranslate"><span class="pre">future_add_to_awaited_by()</span></code> must be followed by aneventual call to the <a class="reference internal" href="#asyncio.future_discard_from_awaited_by" title="asyncio.future_discard_from_awaited_by"><code class="xref py py-func docutils literal notranslate"><span class="pre">future_discard_from_awaited_by()</span></code></a> functionwith the same arguments.</p></dd></dl>
<dl class="py function"><dt class="sig sig-object py" id="asyncio.future_discard_from_awaited_by"><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">future_discard_from_awaited_by</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">future</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">waiter</span></span></em>, <em class="sig-param"><span class="positional-only-separator o"><abbr title="Positional-only parameter separator (PEP 570)"><span class="pre">/</span></abbr></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.future_discard_from_awaited_by" title="Link to this definition">¶</a></dt><dd><p>Record that <em>future</em> is no longer awaited on by <em>waiter</em>.</p><p>Both <em>future</em> and <em>waiter</em> must be instances of<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> or <a class="reference internal" href="asyncio-task.html#asyncio.Task" title="asyncio.Task"><code class="xref py py-class docutils literal notranslate"><span class="pre">Task</span></code></a> or their subclasses, otherwisethe call would have no effect.</p></dd></dl>
</section></section>
<div class="clearer"></div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="Main"> <div class="sphinxsidebarwrapper"> <div> <h3><a href="../contents.html">Table of Contents</a></h3> <ul><li><a class="reference internal" href="#">Call Graph Introspection</a><ul><li><a class="reference internal" href="#low-level-utility-functions">Low level utility functions</a></li></ul></li></ul>
</div> <div> <h4>Previous topic</h4> <p class="topless"><a href="asyncio-exceptions.html" title="previous chapter">Exceptions</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="asyncio-eventloop.html" title="next chapter">Event Loop</a></p> </div> <script> document.addEventListener('DOMContentLoaded', () => { const title = document.querySelector('meta[property="og:title"]').content; const elements = document.querySelectorAll('.improvepage'); const pageurl = window.location.href.split('?')[0]; elements.forEach(element => { const url = new URL(element.href.split('?')[0].replace("-nojs", "")); url.searchParams.set('pagetitle', title); url.searchParams.set('pageurl', pageurl); url.searchParams.set('pagesource', "library/asyncio-graph.rst"); element.href = url.toString(); }); }); </script> <div role="note" aria-label="source link"> <h3>This page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a bug</a></li> <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li> <li> <a href="https://github.com/python/cpython/blob/main/Doc/library/asyncio-graph.rst?plain=1" rel="nofollow">Show source </a> </li> </ul> </div> </div><div id="sidebarbutton" title="Collapse sidebar"><span>«</span></div>
</div> <div class="clearer"></div> </div> <div class="related" role="navigation" aria-label="Related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="asyncio-eventloop.html" title="Event Loop" >next</a> |</li> <li class="right" > <a href="asyncio-exceptions.html" title="Exceptions" >previous</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.15.0a6 Documentation</a> » </li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="ipc.html" >Networking and Interprocess Communication</a> »</li> <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> »</li> <li class="nav-item nav-item-this"><a href="">Call Graph Introspection</a></li> <li class="right">
<div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box"> <input type="submit" value="Go"> </form> </div> | </li> <li class="right"><label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> |</li> </ul> </div> <div class="footer"> © <a href="../copyright.html">Copyright</a> 2001 Python Software Foundation. <br> This page is licensed under the Python Software Foundation License Version 2. <br> Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. <br> See <a href="/license.html">History and License</a> for more information.<br> <br>
The Python Software Foundation is a non-profit corporation.<a href="https://www.python.org/psf/donations/">Please donate.</a><br> <br> Last updated on Mar 10, 2026 (08:58 UTC). <a href="/bugs.html">Found a bug</a>? <br>
Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3. </div>
</body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935<!DOCTYPE html>
<html lang="en" data-content_root="../"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta property="og:title" content="Low-level API Index" /><meta property="og:type" content="website" /><meta property="og:url" content="https://docs.python.org/3/library/asyncio-llapi-index.html" /><meta property="og:site_name" content="Python documentation" /><meta property="og:description" content="This page lists all low-level asyncio APIs. Obtaining the Event Loop:,, asyncio.get_running_loop(), The preferred function to get the running event loop.,, asyncio.get_event_loop(), Get an event lo..." /><meta property="og:image:width" content="1146" /><meta property="og:image:height" content="600" /><meta property="og:image" content="https://docs.python.org/3.15/_images/social_previews/summary_library_asyncio-llapi-index_a52b074a.png" /><meta property="og:image:alt" content="This page lists all low-level asyncio APIs. Obtaining the Event Loop:,, asyncio.get_running_loop(), The preferred function to get the running event loop.,, asyncio.get_event_loop(), Get an event lo..." /><meta name="description" content="This page lists all low-level asyncio APIs. Obtaining the Event Loop:,, asyncio.get_running_loop(), The preferred function to get the running event loop.,, asyncio.get_event_loop(), Get an event lo..." /><meta name="twitter:card" content="summary_large_image" /><meta name="theme-color" content="#3776ab">
<title>Low-level API Index — Python 3.15.0a6 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" /> <link rel="stylesheet" type="text/css" href="../_static/classic.css?v=234b1a7c" /> <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=89a2f22a" /> <link rel="stylesheet" type="text/css" href="../_static/profiling-sampling-visualization.css?v=0c2600ae" /> <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" /> <script src="../_static/documentation_options.js?v=6b7c9ff5"></script> <script src="../_static/doctools.js?v=9bcbadda"></script> <script src="../_static/sphinx_highlight.js?v=dc90522c"></script> <script src="../_static/profiling-sampling-visualization.js?v=9811ed04"></script> <script src="../_static/sidebar.js"></script> <link rel="search" type="application/opensearchdescription+xml" title="Search within Python 3.15.0a6 documentation" href="../_static/opensearch.xml"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="copyright" title="Copyright" href="../copyright.html" /> <link rel="next" title="Developing with asyncio" href="asyncio-dev.html" /> <link rel="prev" title="High-level API Index" href="asyncio-api-index.html" /> <script defer file-types="bz2,epub,zip" data-domain="docs.python.org" src="https://analytics.python.org/js/script.file-downloads.outbound-links.js"></script> <link rel="canonical" href="https://docs.python.org/3/library/asyncio-llapi-index.html">
<style> @media only screen { table.full-width-table { width: 100%; } } </style><link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css"> <link rel="shortcut icon" type="image/png" href="../_static/py.svg"> <script type="text/javascript" src="../_static/copybutton.js"></script> <script type="text/javascript" src="../_static/menu.js"></script> <script type="text/javascript" src="../_static/search-focus.js"></script> <script type="text/javascript" src="../_static/themetoggle.js"></script> <script type="text/javascript" src="../_static/rtd_switcher.js"></script> <meta name="readthedocs-addons-api-version" content="1">
</head><body><div class="mobile-nav"> <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation" aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu"> <nav class="nav-content" role="navigation"> <label for="menuToggler" class="toggler__label"> <span></span> </label> <span class="nav-items-wrapper"> <a href="https://www.python.org/" class="nav-logo"> <img src="../_static/py.svg" alt="Python logo"> </a> <span class="version_switcher_placeholder"></span> <form role="search" class="search" action="../search.html" method="get"> <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon"> <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> </svg> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q"> <input type="submit" value="Go"> </form> </span> </nav> <div class="menu-wrapper"> <nav class="menu" role="navigation" aria-label="main navigation"> <div class="language_switcher_placeholder"></div> <label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> <div> <h3><a href="../contents.html">Table of Contents</a></h3> <ul><li><a class="reference internal" href="#">Low-level API Index</a><ul><li><a class="reference internal" href="#obtaining-the-event-loop">Obtaining the Event Loop</a></li><li><a class="reference internal" href="#event-loop-methods">Event Loop Methods</a></li><li><a class="reference internal" href="#transports">Transports</a></li><li><a class="reference internal" href="#protocols">Protocols</a></li><li><a class="reference internal" href="#event-loop-policies">Event Loop Policies</a></li></ul></li></ul>
</div> <div> <h4>Previous topic</h4> <p class="topless"><a href="asyncio-api-index.html" title="previous chapter">High-level API Index</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="asyncio-dev.html" title="next chapter">Developing with asyncio</a></p> </div> <script> document.addEventListener('DOMContentLoaded', () => { const title = document.querySelector('meta[property="og:title"]').content; const elements = document.querySelectorAll('.improvepage'); const pageurl = window.location.href.split('?')[0]; elements.forEach(element => { const url = new URL(element.href.split('?')[0].replace("-nojs", "")); url.searchParams.set('pagetitle', title); url.searchParams.set('pageurl', pageurl); url.searchParams.set('pagesource', "library/asyncio-llapi-index.rst"); element.href = url.toString(); }); }); </script> <div role="note" aria-label="source link"> <h3>This page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a bug</a></li> <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li> <li> <a href="https://github.com/python/cpython/blob/main/Doc/library/asyncio-llapi-index.rst?plain=1" rel="nofollow">Show source </a> </li> </ul> </div> </nav> </div></div>
<div class="related" role="navigation" aria-label="Related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="asyncio-dev.html" title="Developing with asyncio" accesskey="N">next</a> |</li> <li class="right" > <a href="asyncio-api-index.html" title="High-level API Index" accesskey="P">previous</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.15.0a6 Documentation</a> » </li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="ipc.html" >Networking and Interprocess Communication</a> »</li> <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> »</li> <li class="nav-item nav-item-this"><a href="">Low-level API Index</a></li> <li class="right">
<div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box"> <input type="submit" value="Go"> </form> </div> | </li> <li class="right"><label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> |</li> </ul> </div>
<div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <section id="low-level-api-index"><h1>Low-level API Index<a class="headerlink" href="#low-level-api-index" title="Link to this heading">¶</a></h1><p>This page lists all low-level asyncio APIs.</p><section id="obtaining-the-event-loop"><h2>Obtaining the Event Loop<a class="headerlink" href="#obtaining-the-event-loop" title="Link to this heading">¶</a></h2><table class="full-width-table docutils align-default"><colgroup><col style="width: 50.0%" /><col style="width: 50.0%" /></colgroup><tbody><tr class="row-odd"><td><p><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">asyncio.get_running_loop()</span></code></a></p></td><td><p>The <strong>preferred</strong> function to get the running event loop.</p></td></tr><tr class="row-even"><td><p><a class="reference internal" href="asyncio-eventloop.html#asyncio.get_event_loop" title="asyncio.get_event_loop"><code class="xref py py-func docutils literal notranslate"><span class="pre">asyncio.get_event_loop()</span></code></a></p></td><td><p>Get an event loop instance (running or current via the current policy).</p></td></tr><tr class="row-odd"><td><p><a class="reference internal" href="asyncio-eventloop.html#asyncio.set_event_loop" title="asyncio.set_event_loop"><code class="xref py py-func docutils literal notranslate"><span class="pre">asyncio.set_event_loop()</span></code></a></p></td><td><p>Set the event loop as current via the current policy.</p></td></tr><tr class="row-even"><td><p><a class="reference internal" href="asyncio-eventloop.html#asyncio.new_event_loop" title="asyncio.new_event_loop"><code class="xref py py-func docutils literal notranslate"><span class="pre">asyncio.new_event_loop()</span></code></a></p></td><td><p>Create a new event loop.</p></td></tr></tbody></table><p class="rubric">Examples</p><ul class="simple"><li><p><a class="reference internal" href="asyncio-future.html#asyncio-example-future"><span class="std std-ref">Using asyncio.get_running_loop()</span></a>.</p></li></ul></section><section id="event-loop-methods"><h2>Event Loop Methods<a class="headerlink" href="#event-loop-methods" title="Link to this heading">¶</a></h2><p>See also the main documentation section about the<a class="reference internal" href="asyncio-eventloop.html#asyncio-event-loop-methods"><span class="std std-ref">Event Loop Methods</span></a>.</p><p class="rubric">Lifecycle</p><table class="full-width-table docutils align-default"><colgroup><col style="width: 50.0%" /><col style="width: 50.0%" /></colgroup><tbody><tr class="row-odd"><td><p><a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.run_until_complete" title="asyncio.loop.run_until_complete"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.run_until_complete()</span></code></a></p></td><td><p>Run a Future/Task/awaitable until complete.</p></td></tr><tr class="row-even"><td><p><a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.run_forever" title="asyncio.loop.run_forever"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.run_forever()</span></code></a></p></td><td><p>Run the event loop forever.</p></td></tr><tr class="row-odd"><td><p><a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.stop" title="asyncio.loop.stop"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.stop()</span></code></a></p></td><td><p>Stop the event loop.</p></td></tr><tr class="row-even"><td><p><a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.close" title="asyncio.loop.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.close()</span></code></a></p></td><td><p>Close the event loop.</p></td></tr><tr class="row-odd"><td><p><a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.is_running" title="asyncio.loop.is_running"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.is_running()</span></code></a></p></td><td><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the event loop is running.</p></td></tr><tr class="row-even"><td><p><a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.is_closed" title="asyncio.loop.is_closed"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.is_closed()</span></code></a></p></td><td><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the event loop is closed.</p></td></tr><tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">await</span></code> <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.shutdown_asyncgens" title="asyncio.loop.shutdown_asyncgens"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.shutdown_asyncgens()</span></code></a></p></td><td><p>Close asynchronous generators.</p></td></tr></tbody></table><p class="rubric">Debugging</p><table class="full-width-table docutils align-default"><colgroup><col style="width: 50.0%" /><col style="width: 50.0%" /></colgroup><tbody><tr class="row-odd"><td><p><a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.set_debug" title="asyncio.loop.set_debug"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.set_debug()</span></code></a></p></td><td><p>Enable or disable the debug mode.</p></td></tr><tr class="row-even"><td><p><a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.get_debug" title="asyncio.loop.get_debug"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.get_debug()</span></code></a></p></td><td><p>Get the current debug mode.</p></td></tr></tbody></table><p class="rubric">Scheduling Callbacks</p><table class="full-width-table docutils align-default"><colgroup><col style="width: 50.0%" /><col style="width: 50.0%" /></colgroup><tbody><tr class="row-odd"><td><p><a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.call_soon" title="asyncio.loop.call_soon"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.call_soon()</span></code></a></p></td><td><p>Invoke a callback soon.</p></td></tr><tr class="row-even"><td><p><a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.call_soon_threadsafe" title="asyncio.loop.call_soon_threadsafe"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.call_soon_threadsafe()</span></code></a></p></td><td><p>A thread-safe variant of <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.call_soon" title="asyncio.loop.call_soon"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.call_soon()</span></code></a>.</p></td></tr><tr class="row-odd"><td><p><a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.call_later" title="asyncio.loop.call_later"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.call_later()</span></code></a></p></td><td><p>Invoke a callback <em>after</em> the given time.</p></td></tr><tr class="row-even"><td><p><a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.call_at" title="asyncio.loop.call_at"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.call_at()</span></code></a></p></td><td><p>Invoke a callback <em>at</em> the given time.</p></td></tr></tbody></table><p class="rubric">Thread/Interpreter/Process Pool</p><table class="full-width-table docutils align-default"><colgroup><col style="width: 50.0%" /><col style="width: 50.0%" /></colgroup><tbody><tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">await</span></code> <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></td><td><p>Run a CPU-bound or other blocking function ina <a class="reference internal" href="concurrent.futures.html#module-concurrent.futures" title="concurrent.futures: Execute computations concurrently using threads or processes."><code class="xref py py-mod docutils literal notranslate"><span class="pre">concurrent.futures</span></code></a> executor.</p></td></tr><tr class="row-even"><td><p><a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.set_default_executor" title="asyncio.loop.set_default_executor"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.set_default_executor()</span></code></a></p></td><td><p>Set the default executor for <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></td></tr></tbody></table><p class="rubric">Tasks and Futures</p><table class="full-width-table docutils align-default"><colgroup><col style="width: 50.0%" /><col style="width: 50.0%" /></colgroup><tbody><tr class="row-odd"><td><p><a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.create_future" title="asyncio.loop.create_future"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.create_future()</span></code></a></p></td><td><p>Create 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> object.</p></td></tr><tr class="row-even"><td><p><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></p></td><td><p>Schedule coroutine as a <a class="reference internal" href="asyncio-task.html#asyncio.Task" title="asyncio.Task"><code class="xref py py-class docutils literal notranslate"><span class="pre">Task</span></code></a>.</p></td></tr><tr class="row-odd"><td><p><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()</span></code></a></p></td><td><p>Set a factory used by <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> tocreate <a class="reference internal" href="asyncio-task.html#asyncio.Task" title="asyncio.Task"><code class="xref py py-class docutils literal notranslate"><span class="pre">Tasks</span></code></a>.</p></td></tr><tr class="row-even"><td><p><a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.get_task_factory" title="asyncio.loop.get_task_factory"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.get_task_factory()</span></code></a></p></td><td><p>Get the factory <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> usesto create <a class="reference internal" href="asyncio-task.html#asyncio.Task" title="asyncio.Task"><code class="xref py py-class docutils literal notranslate"><span class="pre">Tasks</span></code></a>.</p></td></tr></tbody></table><p class="rubric">DNS</p><table class="full-width-table docutils align-default"><colgroup><col style="width: 50.0%" /><col style="width: 50.0%" /></colgroup><tbody><tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">await</span></code> <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.getaddrinfo" title="asyncio.loop.getaddrinfo"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.getaddrinfo()</span></code></a></p></td><td><p>Asynchronous version of <a class="reference internal" href="socket.html#socket.getaddrinfo" title="socket.getaddrinfo"><code class="xref py py-meth docutils literal notranslate"><span class="pre">socket.getaddrinfo()</span></code></a>.</p></td></tr><tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">await</span></code> <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.getnameinfo" title="asyncio.loop.getnameinfo"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.getnameinfo()</span></code></a></p></td><td><p>Asynchronous version of <a class="reference internal" href="socket.html#socket.getnameinfo" title="socket.getnameinfo"><code class="xref py py-meth docutils literal notranslate"><span class="pre">socket.getnameinfo()</span></code></a>.</p></td></tr></tbody></table><p class="rubric">Networking and IPC</p><table class="full-width-table docutils align-default"><colgroup><col style="width: 50.0%" /><col style="width: 50.0%" /></colgroup><tbody><tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">await</span></code> <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.create_connection" title="asyncio.loop.create_connection"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.create_connection()</span></code></a></p></td><td><p>Open a TCP connection.</p></td></tr><tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">await</span></code> <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.create_server" title="asyncio.loop.create_server"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.create_server()</span></code></a></p></td><td><p>Create a TCP server.</p></td></tr><tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">await</span></code> <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.create_unix_connection" title="asyncio.loop.create_unix_connection"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.create_unix_connection()</span></code></a></p></td><td><p>Open a Unix socket connection.</p></td></tr><tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">await</span></code> <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.create_unix_server" title="asyncio.loop.create_unix_server"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.create_unix_server()</span></code></a></p></td><td><p>Create a Unix socket server.</p></td></tr><tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">await</span></code> <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.connect_accepted_socket" title="asyncio.loop.connect_accepted_socket"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.connect_accepted_socket()</span></code></a></p></td><td><p>Wrap a <a class="reference internal" href="socket.html#socket.socket" title="socket.socket"><code class="xref py py-class docutils literal notranslate"><span class="pre">socket</span></code></a> into a <code class="docutils literal notranslate"><span class="pre">(transport,</span> <span class="pre">protocol)</span></code>pair.</p></td></tr><tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">await</span></code> <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.create_datagram_endpoint" title="asyncio.loop.create_datagram_endpoint"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.create_datagram_endpoint()</span></code></a></p></td><td><p>Open a datagram (UDP) connection.</p></td></tr><tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">await</span></code> <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.sendfile" title="asyncio.loop.sendfile"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.sendfile()</span></code></a></p></td><td><p>Send a file over a transport.</p></td></tr><tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">await</span></code> <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.start_tls" title="asyncio.loop.start_tls"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.start_tls()</span></code></a></p></td><td><p>Upgrade an existing connection to TLS.</p></td></tr><tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">await</span></code> <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.connect_read_pipe" title="asyncio.loop.connect_read_pipe"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.connect_read_pipe()</span></code></a></p></td><td><p>Wrap a read end of a pipe into a <code class="docutils literal notranslate"><span class="pre">(transport,</span> <span class="pre">protocol)</span></code> pair.</p></td></tr><tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">await</span></code> <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.connect_write_pipe" title="asyncio.loop.connect_write_pipe"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.connect_write_pipe()</span></code></a></p></td><td><p>Wrap a write end of a pipe into a <code class="docutils literal notranslate"><span class="pre">(transport,</span> <span class="pre">protocol)</span></code> pair.</p></td></tr></tbody></table><p class="rubric">Sockets</p><table class="full-width-table docutils align-default"><colgroup><col style="width: 50.0%" /><col style="width: 50.0%" /></colgroup><tbody><tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">await</span></code> <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.sock_recv" title="asyncio.loop.sock_recv"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.sock_recv()</span></code></a></p></td><td><p>Receive data from the <a class="reference internal" href="socket.html#socket.socket" title="socket.socket"><code class="xref py py-class docutils literal notranslate"><span class="pre">socket</span></code></a>.</p></td></tr><tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">await</span></code> <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.sock_recv_into" title="asyncio.loop.sock_recv_into"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.sock_recv_into()</span></code></a></p></td><td><p>Receive data from the <a class="reference internal" href="socket.html#socket.socket" title="socket.socket"><code class="xref py py-class docutils literal notranslate"><span class="pre">socket</span></code></a> into a buffer.</p></td></tr><tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">await</span></code> <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.sock_recvfrom" title="asyncio.loop.sock_recvfrom"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.sock_recvfrom()</span></code></a></p></td><td><p>Receive a datagram from the <a class="reference internal" href="socket.html#socket.socket" title="socket.socket"><code class="xref py py-class docutils literal notranslate"><span class="pre">socket</span></code></a>.</p></td></tr><tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">await</span></code> <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.sock_recvfrom_into" title="asyncio.loop.sock_recvfrom_into"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.sock_recvfrom_into()</span></code></a></p></td><td><p>Receive a datagram from the <a class="reference internal" href="socket.html#socket.socket" title="socket.socket"><code class="xref py py-class docutils literal notranslate"><span class="pre">socket</span></code></a> into a buffer.</p></td></tr><tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">await</span></code> <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.sock_sendall" title="asyncio.loop.sock_sendall"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.sock_sendall()</span></code></a></p></td><td><p>Send data to the <a class="reference internal" href="socket.html#socket.socket" title="socket.socket"><code class="xref py py-class docutils literal notranslate"><span class="pre">socket</span></code></a>.</p></td></tr><tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">await</span></code> <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.sock_sendto" title="asyncio.loop.sock_sendto"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.sock_sendto()</span></code></a></p></td><td><p>Send a datagram via the <a class="reference internal" href="socket.html#socket.socket" title="socket.socket"><code class="xref py py-class docutils literal notranslate"><span class="pre">socket</span></code></a> to the given address.</p></td></tr><tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">await</span></code> <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.sock_connect" title="asyncio.loop.sock_connect"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.sock_connect()</span></code></a></p></td><td><p>Connect the <a class="reference internal" href="socket.html#socket.socket" title="socket.socket"><code class="xref py py-class docutils literal notranslate"><span class="pre">socket</span></code></a>.</p></td></tr><tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">await</span></code> <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.sock_accept" title="asyncio.loop.sock_accept"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.sock_accept()</span></code></a></p></td><td><p>Accept a <a class="reference internal" href="socket.html#socket.socket" title="socket.socket"><code class="xref py py-class docutils literal notranslate"><span class="pre">socket</span></code></a> connection.</p></td></tr><tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">await</span></code> <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.sock_sendfile" title="asyncio.loop.sock_sendfile"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.sock_sendfile()</span></code></a></p></td><td><p>Send a file over the <a class="reference internal" href="socket.html#socket.socket" title="socket.socket"><code class="xref py py-class docutils literal notranslate"><span class="pre">socket</span></code></a>.</p></td></tr><tr class="row-even"><td><p><a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.add_reader" title="asyncio.loop.add_reader"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.add_reader()</span></code></a></p></td><td><p>Start watching a file descriptor for read availability.</p></td></tr><tr class="row-odd"><td><p><a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.remove_reader" title="asyncio.loop.remove_reader"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.remove_reader()</span></code></a></p></td><td><p>Stop watching a file descriptor for read availability.</p></td></tr><tr class="row-even"><td><p><a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.add_writer" title="asyncio.loop.add_writer"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.add_writer()</span></code></a></p></td><td><p>Start watching a file descriptor for write availability.</p></td></tr><tr class="row-odd"><td><p><a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.remove_writer" title="asyncio.loop.remove_writer"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.remove_writer()</span></code></a></p></td><td><p>Stop watching a file descriptor for write availability.</p></td></tr></tbody></table><p class="rubric">Unix Signals</p><table class="full-width-table docutils align-default"><colgroup><col style="width: 50.0%" /><col style="width: 50.0%" /></colgroup><tbody><tr class="row-odd"><td><p><a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.add_signal_handler" title="asyncio.loop.add_signal_handler"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.add_signal_handler()</span></code></a></p></td><td><p>Add a handler for a <a class="reference internal" href="signal.html#module-signal" title="signal: Set handlers for asynchronous events."><code class="xref py py-mod docutils literal notranslate"><span class="pre">signal</span></code></a>.</p></td></tr><tr class="row-even"><td><p><a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.remove_signal_handler" title="asyncio.loop.remove_signal_handler"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.remove_signal_handler()</span></code></a></p></td><td><p>Remove a handler for a <a class="reference internal" href="signal.html#module-signal" title="signal: Set handlers for asynchronous events."><code class="xref py py-mod docutils literal notranslate"><span class="pre">signal</span></code></a>.</p></td></tr></tbody></table><p class="rubric">Subprocesses</p><table class="full-width-table docutils align-default"><colgroup><col style="width: 50.0%" /><col style="width: 50.0%" /></colgroup><tbody><tr class="row-odd"><td><p><a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.subprocess_exec" title="asyncio.loop.subprocess_exec"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.subprocess_exec()</span></code></a></p></td><td><p>Spawn a subprocess.</p></td></tr><tr class="row-even"><td><p><a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.subprocess_shell" title="asyncio.loop.subprocess_shell"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.subprocess_shell()</span></code></a></p></td><td><p>Spawn a subprocess from a shell command.</p></td></tr></tbody></table><p class="rubric">Error Handling</p><table class="full-width-table docutils align-default"><colgroup><col style="width: 50.0%" /><col style="width: 50.0%" /></colgroup><tbody><tr class="row-odd"><td><p><a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.call_exception_handler" title="asyncio.loop.call_exception_handler"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.call_exception_handler()</span></code></a></p></td><td><p>Call the exception handler.</p></td></tr><tr class="row-even"><td><p><a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.set_exception_handler" title="asyncio.loop.set_exception_handler"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.set_exception_handler()</span></code></a></p></td><td><p>Set a new exception handler.</p></td></tr><tr class="row-odd"><td><p><a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.get_exception_handler" title="asyncio.loop.get_exception_handler"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.get_exception_handler()</span></code></a></p></td><td><p>Get the current exception handler.</p></td></tr><tr class="row-even"><td><p><a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.default_exception_handler" title="asyncio.loop.default_exception_handler"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.default_exception_handler()</span></code></a></p></td><td><p>The default exception handler implementation.</p></td></tr></tbody></table><p class="rubric">Examples</p><ul class="simple"><li><p><a class="reference internal" href="asyncio-eventloop.html#asyncio-example-lowlevel-helloworld"><span class="std std-ref">Using asyncio.new_event_loop() and loop.run_forever()</span></a>.</p></li><li><p><a class="reference internal" href="asyncio-eventloop.html#asyncio-example-call-later"><span class="std std-ref">Using loop.call_later()</span></a>.</p></li><li><p>Using <code class="docutils literal notranslate"><span class="pre">loop.create_connection()</span></code> to implement<a class="reference internal" href="asyncio-protocol.html#asyncio-example-tcp-echo-client-protocol"><span class="std std-ref">an echo-client</span></a>.</p></li><li><p>Using <code class="docutils literal notranslate"><span class="pre">loop.create_connection()</span></code> to<a class="reference internal" href="asyncio-protocol.html#asyncio-example-create-connection"><span class="std std-ref">connect a socket</span></a>.</p></li><li><p><a class="reference internal" href="asyncio-eventloop.html#asyncio-example-watch-fd"><span class="std std-ref">Using add_reader() to watch an FD for read events</span></a>.</p></li><li><p><a class="reference internal" href="asyncio-eventloop.html#asyncio-example-unix-signals"><span class="std std-ref">Using loop.add_signal_handler()</span></a>.</p></li><li><p><a class="reference internal" href="asyncio-protocol.html#asyncio-example-subprocess-proto"><span class="std std-ref">Using loop.subprocess_exec()</span></a>.</p></li></ul></section><section id="transports"><h2>Transports<a class="headerlink" href="#transports" title="Link to this heading">¶</a></h2><p>All transports implement the following methods:</p><table class="full-width-table docutils align-default"><colgroup><col style="width: 50.0%" /><col style="width: 50.0%" /></colgroup><tbody><tr class="row-odd"><td><p><a class="reference internal" href="asyncio-protocol.html#asyncio.BaseTransport.close" title="asyncio.BaseTransport.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">transport.close()</span></code></a></p></td><td><p>Close the transport.</p></td></tr><tr class="row-even"><td><p><a class="reference internal" href="asyncio-protocol.html#asyncio.BaseTransport.is_closing" title="asyncio.BaseTransport.is_closing"><code class="xref py py-meth docutils literal notranslate"><span class="pre">transport.is_closing()</span></code></a></p></td><td><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the transport is closing or is closed.</p></td></tr><tr class="row-odd"><td><p><a class="reference internal" href="asyncio-protocol.html#asyncio.BaseTransport.get_extra_info" title="asyncio.BaseTransport.get_extra_info"><code class="xref py py-meth docutils literal notranslate"><span class="pre">transport.get_extra_info()</span></code></a></p></td><td><p>Request for information about the transport.</p></td></tr><tr class="row-even"><td><p><a class="reference internal" href="asyncio-protocol.html#asyncio.BaseTransport.set_protocol" title="asyncio.BaseTransport.set_protocol"><code class="xref py py-meth docutils literal notranslate"><span class="pre">transport.set_protocol()</span></code></a></p></td><td><p>Set a new protocol.</p></td></tr><tr class="row-odd"><td><p><a class="reference internal" href="asyncio-protocol.html#asyncio.BaseTransport.get_protocol" title="asyncio.BaseTransport.get_protocol"><code class="xref py py-meth docutils literal notranslate"><span class="pre">transport.get_protocol()</span></code></a></p></td><td><p>Return the current protocol.</p></td></tr></tbody></table><p>Transports that can receive data (TCP and Unix connections,pipes, etc). Returned from methods like<a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.create_connection" title="asyncio.loop.create_connection"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.create_connection()</span></code></a>, <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.create_unix_connection" title="asyncio.loop.create_unix_connection"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.create_unix_connection()</span></code></a>,<a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.connect_read_pipe" title="asyncio.loop.connect_read_pipe"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.connect_read_pipe()</span></code></a>, etc:</p><p class="rubric">Read Transports</p><table class="full-width-table docutils align-default"><colgroup><col style="width: 50.0%" /><col style="width: 50.0%" /></colgroup><tbody><tr class="row-odd"><td><p><a class="reference internal" href="asyncio-protocol.html#asyncio.ReadTransport.is_reading" title="asyncio.ReadTransport.is_reading"><code class="xref py py-meth docutils literal notranslate"><span class="pre">transport.is_reading()</span></code></a></p></td><td><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the transport is receiving.</p></td></tr><tr class="row-even"><td><p><a class="reference internal" href="asyncio-protocol.html#asyncio.ReadTransport.pause_reading" title="asyncio.ReadTransport.pause_reading"><code class="xref py py-meth docutils literal notranslate"><span class="pre">transport.pause_reading()</span></code></a></p></td><td><p>Pause receiving.</p></td></tr><tr class="row-odd"><td><p><a class="reference internal" href="asyncio-protocol.html#asyncio.ReadTransport.resume_reading" title="asyncio.ReadTransport.resume_reading"><code class="xref py py-meth docutils literal notranslate"><span class="pre">transport.resume_reading()</span></code></a></p></td><td><p>Resume receiving.</p></td></tr></tbody></table><p>Transports that can Send data (TCP and Unix connections,pipes, etc). Returned from methods like<a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.create_connection" title="asyncio.loop.create_connection"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.create_connection()</span></code></a>, <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.create_unix_connection" title="asyncio.loop.create_unix_connection"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.create_unix_connection()</span></code></a>,<a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.connect_write_pipe" title="asyncio.loop.connect_write_pipe"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.connect_write_pipe()</span></code></a>, etc:</p><p class="rubric">Write Transports</p><table class="full-width-table docutils align-default"><colgroup><col style="width: 50.0%" /><col style="width: 50.0%" /></colgroup><tbody><tr class="row-odd"><td><p><a class="reference internal" href="asyncio-protocol.html#asyncio.WriteTransport.write" title="asyncio.WriteTransport.write"><code class="xref py py-meth docutils literal notranslate"><span class="pre">transport.write()</span></code></a></p></td><td><p>Write data to the transport.</p></td></tr><tr class="row-even"><td><p><a class="reference internal" href="asyncio-protocol.html#asyncio.WriteTransport.writelines" title="asyncio.WriteTransport.writelines"><code class="xref py py-meth docutils literal notranslate"><span class="pre">transport.writelines()</span></code></a></p></td><td><p>Write buffers to the transport.</p></td></tr><tr class="row-odd"><td><p><a class="reference internal" href="asyncio-protocol.html#asyncio.WriteTransport.can_write_eof" title="asyncio.WriteTransport.can_write_eof"><code class="xref py py-meth docutils literal notranslate"><span class="pre">transport.can_write_eof()</span></code></a></p></td><td><p>Return <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> if the transport supports sending EOF.</p></td></tr><tr class="row-even"><td><p><a class="reference internal" href="asyncio-protocol.html#asyncio.WriteTransport.write_eof" title="asyncio.WriteTransport.write_eof"><code class="xref py py-meth docutils literal notranslate"><span class="pre">transport.write_eof()</span></code></a></p></td><td><p>Close and send EOF after flushing buffered data.</p></td></tr><tr class="row-odd"><td><p><a class="reference internal" href="asyncio-protocol.html#asyncio.WriteTransport.abort" title="asyncio.WriteTransport.abort"><code class="xref py py-meth docutils literal notranslate"><span class="pre">transport.abort()</span></code></a></p></td><td><p>Close the transport immediately.</p></td></tr><tr class="row-even"><td><p><a class="reference internal" href="asyncio-protocol.html#asyncio.WriteTransport.get_write_buffer_size" title="asyncio.WriteTransport.get_write_buffer_size"><code class="xref py py-meth docutils literal notranslate"><span class="pre">transport.get_write_buffer_size()</span></code></a></p></td><td><p>Return the current size of the output buffer.</p></td></tr><tr class="row-odd"><td><p><a class="reference internal" href="asyncio-protocol.html#asyncio.WriteTransport.get_write_buffer_limits" title="asyncio.WriteTransport.get_write_buffer_limits"><code class="xref py py-meth docutils literal notranslate"><span class="pre">transport.get_write_buffer_limits()</span></code></a></p></td><td><p>Return high and low water marks for write flow control.</p></td></tr><tr class="row-even"><td><p><a class="reference internal" href="asyncio-protocol.html#asyncio.WriteTransport.set_write_buffer_limits" title="asyncio.WriteTransport.set_write_buffer_limits"><code class="xref py py-meth docutils literal notranslate"><span class="pre">transport.set_write_buffer_limits()</span></code></a></p></td><td><p>Set new high and low water marks for write flow control.</p></td></tr></tbody></table><p>Transports returned by <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.create_datagram_endpoint" title="asyncio.loop.create_datagram_endpoint"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.create_datagram_endpoint()</span></code></a>:</p><p class="rubric">Datagram Transports</p><table class="full-width-table docutils align-default"><colgroup><col style="width: 50.0%" /><col style="width: 50.0%" /></colgroup><tbody><tr class="row-odd"><td><p><a class="reference internal" href="asyncio-protocol.html#asyncio.DatagramTransport.sendto" title="asyncio.DatagramTransport.sendto"><code class="xref py py-meth docutils literal notranslate"><span class="pre">transport.sendto()</span></code></a></p></td><td><p>Send data to the remote peer.</p></td></tr><tr class="row-even"><td><p><a class="reference internal" href="asyncio-protocol.html#asyncio.DatagramTransport.abort" title="asyncio.DatagramTransport.abort"><code class="xref py py-meth docutils literal notranslate"><span class="pre">transport.abort()</span></code></a></p></td><td><p>Close the transport immediately.</p></td></tr></tbody></table><p>Low-level transport abstraction over subprocesses.Returned by <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.subprocess_exec" title="asyncio.loop.subprocess_exec"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.subprocess_exec()</span></code></a> and<a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.subprocess_shell" title="asyncio.loop.subprocess_shell"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.subprocess_shell()</span></code></a>:</p><p class="rubric">Subprocess Transports</p><table class="full-width-table docutils align-default"><colgroup><col style="width: 50.0%" /><col style="width: 50.0%" /></colgroup><tbody><tr class="row-odd"><td><p><a class="reference internal" href="asyncio-protocol.html#asyncio.SubprocessTransport.get_pid" title="asyncio.SubprocessTransport.get_pid"><code class="xref py py-meth docutils literal notranslate"><span class="pre">transport.get_pid()</span></code></a></p></td><td><p>Return the subprocess process id.</p></td></tr><tr class="row-even"><td><p><a class="reference internal" href="asyncio-protocol.html#asyncio.SubprocessTransport.get_pipe_transport" title="asyncio.SubprocessTransport.get_pipe_transport"><code class="xref py py-meth docutils literal notranslate"><span class="pre">transport.get_pipe_transport()</span></code></a></p></td><td><p>Return the transport for the requested communication pipe(<em>stdin</em>, <em>stdout</em>, or <em>stderr</em>).</p></td></tr><tr class="row-odd"><td><p><a class="reference internal" href="asyncio-protocol.html#asyncio.SubprocessTransport.get_returncode" title="asyncio.SubprocessTransport.get_returncode"><code class="xref py py-meth docutils literal notranslate"><span class="pre">transport.get_returncode()</span></code></a></p></td><td><p>Return the subprocess return code.</p></td></tr><tr class="row-even"><td><p><a class="reference internal" href="asyncio-protocol.html#asyncio.SubprocessTransport.kill" title="asyncio.SubprocessTransport.kill"><code class="xref py py-meth docutils literal notranslate"><span class="pre">transport.kill()</span></code></a></p></td><td><p>Kill the subprocess.</p></td></tr><tr class="row-odd"><td><p><a class="reference internal" href="asyncio-protocol.html#asyncio.SubprocessTransport.send_signal" title="asyncio.SubprocessTransport.send_signal"><code class="xref py py-meth docutils literal notranslate"><span class="pre">transport.send_signal()</span></code></a></p></td><td><p>Send a signal to the subprocess.</p></td></tr><tr class="row-even"><td><p><a class="reference internal" href="asyncio-protocol.html#asyncio.SubprocessTransport.terminate" title="asyncio.SubprocessTransport.terminate"><code class="xref py py-meth docutils literal notranslate"><span class="pre">transport.terminate()</span></code></a></p></td><td><p>Stop the subprocess.</p></td></tr><tr class="row-odd"><td><p><a class="reference internal" href="asyncio-protocol.html#asyncio.SubprocessTransport.close" title="asyncio.SubprocessTransport.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">transport.close()</span></code></a></p></td><td><p>Kill the subprocess and close all pipes.</p></td></tr></tbody></table></section><section id="protocols"><h2>Protocols<a class="headerlink" href="#protocols" title="Link to this heading">¶</a></h2><p>Protocol classes can implement the following <strong>callback methods</strong>:</p><table class="full-width-table docutils align-default"><colgroup><col style="width: 50.0%" /><col style="width: 50.0%" /></colgroup><tbody><tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">callback</span></code> <a class="reference internal" href="asyncio-protocol.html#asyncio.BaseProtocol.connection_made" title="asyncio.BaseProtocol.connection_made"><code class="xref py py-meth docutils literal notranslate"><span class="pre">connection_made()</span></code></a></p></td><td><p>Called when a connection is made.</p></td></tr><tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">callback</span></code> <a class="reference internal" href="asyncio-protocol.html#asyncio.BaseProtocol.connection_lost" title="asyncio.BaseProtocol.connection_lost"><code class="xref py py-meth docutils literal notranslate"><span class="pre">connection_lost()</span></code></a></p></td><td><p>Called when the connection is lost or closed.</p></td></tr><tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">callback</span></code> <a class="reference internal" href="asyncio-protocol.html#asyncio.BaseProtocol.pause_writing" title="asyncio.BaseProtocol.pause_writing"><code class="xref py py-meth docutils literal notranslate"><span class="pre">pause_writing()</span></code></a></p></td><td><p>Called when the transport’s buffer goes over the high water mark.</p></td></tr><tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">callback</span></code> <a class="reference internal" href="asyncio-protocol.html#asyncio.BaseProtocol.resume_writing" title="asyncio.BaseProtocol.resume_writing"><code class="xref py py-meth docutils literal notranslate"><span class="pre">resume_writing()</span></code></a></p></td><td><p>Called when the transport’s buffer drains below the low water mark.</p></td></tr></tbody></table><p class="rubric">Streaming Protocols (TCP, Unix Sockets, Pipes)</p><table class="full-width-table docutils align-default"><colgroup><col style="width: 50.0%" /><col style="width: 50.0%" /></colgroup><tbody><tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">callback</span></code> <a class="reference internal" href="asyncio-protocol.html#asyncio.Protocol.data_received" title="asyncio.Protocol.data_received"><code class="xref py py-meth docutils literal notranslate"><span class="pre">data_received()</span></code></a></p></td><td><p>Called when some data is received.</p></td></tr><tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">callback</span></code> <a class="reference internal" href="asyncio-protocol.html#asyncio.Protocol.eof_received" title="asyncio.Protocol.eof_received"><code class="xref py py-meth docutils literal notranslate"><span class="pre">eof_received()</span></code></a></p></td><td><p>Called when an EOF is received.</p></td></tr></tbody></table><p class="rubric">Buffered Streaming Protocols</p><table class="full-width-table docutils align-default"><colgroup><col style="width: 50.0%" /><col style="width: 50.0%" /></colgroup><tbody><tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">callback</span></code> <a class="reference internal" href="asyncio-protocol.html#asyncio.BufferedProtocol.get_buffer" title="asyncio.BufferedProtocol.get_buffer"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_buffer()</span></code></a></p></td><td><p>Called to allocate a new receive buffer.</p></td></tr><tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">callback</span></code> <a class="reference internal" href="asyncio-protocol.html#asyncio.BufferedProtocol.buffer_updated" title="asyncio.BufferedProtocol.buffer_updated"><code class="xref py py-meth docutils literal notranslate"><span class="pre">buffer_updated()</span></code></a></p></td><td><p>Called when the buffer was updated with the received data.</p></td></tr><tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">callback</span></code> <a class="reference internal" href="asyncio-protocol.html#asyncio.BufferedProtocol.eof_received" title="asyncio.BufferedProtocol.eof_received"><code class="xref py py-meth docutils literal notranslate"><span class="pre">eof_received()</span></code></a></p></td><td><p>Called when an EOF is received.</p></td></tr></tbody></table><p class="rubric">Datagram Protocols</p><table class="full-width-table docutils align-default"><colgroup><col style="width: 50.0%" /><col style="width: 50.0%" /></colgroup><tbody><tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">callback</span></code> <a class="reference internal" href="asyncio-protocol.html#asyncio.DatagramProtocol.datagram_received" title="asyncio.DatagramProtocol.datagram_received"><code class="xref py py-meth docutils literal notranslate"><span class="pre">datagram_received()</span></code></a></p></td><td><p>Called when a datagram is received.</p></td></tr><tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">callback</span></code> <a class="reference internal" href="asyncio-protocol.html#asyncio.DatagramProtocol.error_received" title="asyncio.DatagramProtocol.error_received"><code class="xref py py-meth docutils literal notranslate"><span class="pre">error_received()</span></code></a></p></td><td><p>Called when a previous send or receive operation raises an<a class="reference internal" href="exceptions.html#OSError" title="OSError"><code class="xref py py-class docutils literal notranslate"><span class="pre">OSError</span></code></a>.</p></td></tr></tbody></table><p class="rubric">Subprocess Protocols</p><table class="full-width-table docutils align-default"><colgroup><col style="width: 50.0%" /><col style="width: 50.0%" /></colgroup><tbody><tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">callback</span></code> <a class="reference internal" href="asyncio-protocol.html#asyncio.SubprocessProtocol.pipe_data_received" title="asyncio.SubprocessProtocol.pipe_data_received"><code class="xref py py-meth docutils literal notranslate"><span class="pre">pipe_data_received()</span></code></a></p></td><td><p>Called when the child process writes data into its<em>stdout</em> or <em>stderr</em> pipe.</p></td></tr><tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">callback</span></code> <a class="reference internal" href="asyncio-protocol.html#asyncio.SubprocessProtocol.pipe_connection_lost" title="asyncio.SubprocessProtocol.pipe_connection_lost"><code class="xref py py-meth docutils literal notranslate"><span class="pre">pipe_connection_lost()</span></code></a></p></td><td><p>Called when one of the pipes communicating withthe child process is closed.</p></td></tr><tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">callback</span></code> <a class="reference internal" href="asyncio-protocol.html#asyncio.SubprocessProtocol.process_exited" title="asyncio.SubprocessProtocol.process_exited"><code class="xref py py-meth docutils literal notranslate"><span class="pre">process_exited()</span></code></a></p></td><td><p>Called when the child process has exited. It can be called before<a class="reference internal" href="asyncio-protocol.html#asyncio.SubprocessProtocol.pipe_data_received" title="asyncio.SubprocessProtocol.pipe_data_received"><code class="xref py py-meth docutils literal notranslate"><span class="pre">pipe_data_received()</span></code></a> and<a class="reference internal" href="asyncio-protocol.html#asyncio.SubprocessProtocol.pipe_connection_lost" title="asyncio.SubprocessProtocol.pipe_connection_lost"><code class="xref py py-meth docutils literal notranslate"><span class="pre">pipe_connection_lost()</span></code></a> methods.</p></td></tr></tbody></table></section><section id="event-loop-policies"><h2>Event Loop Policies<a class="headerlink" href="#event-loop-policies" title="Link to this heading">¶</a></h2><p>Policies is a low-level mechanism to alter the behavior offunctions like <a class="reference internal" href="asyncio-eventloop.html#asyncio.get_event_loop" title="asyncio.get_event_loop"><code class="xref py py-func docutils literal notranslate"><span class="pre">asyncio.get_event_loop()</span></code></a>. See alsothe main <a class="reference internal" href="asyncio-policy.html#asyncio-policies"><span class="std std-ref">policies section</span></a> for moredetails.</p><p class="rubric">Accessing Policies</p><table class="full-width-table docutils align-default"><colgroup><col style="width: 50.0%" /><col style="width: 50.0%" /></colgroup><tbody><tr class="row-odd"><td><p><a class="reference internal" href="asyncio-policy.html#asyncio.get_event_loop_policy" title="asyncio.get_event_loop_policy"><code class="xref py py-meth docutils literal notranslate"><span class="pre">asyncio.get_event_loop_policy()</span></code></a></p></td><td><p>Return the current process-wide policy.</p></td></tr><tr class="row-even"><td><p><a class="reference internal" href="asyncio-policy.html#asyncio.set_event_loop_policy" title="asyncio.set_event_loop_policy"><code class="xref py py-meth docutils literal notranslate"><span class="pre">asyncio.set_event_loop_policy()</span></code></a></p></td><td><p>Set a new process-wide policy.</p></td></tr><tr class="row-odd"><td><p><a class="reference internal" href="asyncio-policy.html#asyncio.AbstractEventLoopPolicy" title="asyncio.AbstractEventLoopPolicy"><code class="xref py py-class docutils literal notranslate"><span class="pre">AbstractEventLoopPolicy</span></code></a></p></td><td><p>Base class for policy objects.</p></td></tr></tbody></table></section></section>
<div class="clearer"></div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="Main"> <div class="sphinxsidebarwrapper"> <div> <h3><a href="../contents.html">Table of Contents</a></h3> <ul><li><a class="reference internal" href="#">Low-level API Index</a><ul><li><a class="reference internal" href="#obtaining-the-event-loop">Obtaining the Event Loop</a></li><li><a class="reference internal" href="#event-loop-methods">Event Loop Methods</a></li><li><a class="reference internal" href="#transports">Transports</a></li><li><a class="reference internal" href="#protocols">Protocols</a></li><li><a class="reference internal" href="#event-loop-policies">Event Loop Policies</a></li></ul></li></ul>
</div> <div> <h4>Previous topic</h4> <p class="topless"><a href="asyncio-api-index.html" title="previous chapter">High-level API Index</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="asyncio-dev.html" title="next chapter">Developing with asyncio</a></p> </div> <script> document.addEventListener('DOMContentLoaded', () => { const title = document.querySelector('meta[property="og:title"]').content; const elements = document.querySelectorAll('.improvepage'); const pageurl = window.location.href.split('?')[0]; elements.forEach(element => { const url = new URL(element.href.split('?')[0].replace("-nojs", "")); url.searchParams.set('pagetitle', title); url.searchParams.set('pageurl', pageurl); url.searchParams.set('pagesource', "library/asyncio-llapi-index.rst"); element.href = url.toString(); }); }); </script> <div role="note" aria-label="source link"> <h3>This page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a bug</a></li> <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li> <li> <a href="https://github.com/python/cpython/blob/main/Doc/library/asyncio-llapi-index.rst?plain=1" rel="nofollow">Show source </a> </li> </ul> </div> </div><div id="sidebarbutton" title="Collapse sidebar"><span>«</span></div>
</div> <div class="clearer"></div> </div> <div class="related" role="navigation" aria-label="Related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="asyncio-dev.html" title="Developing with asyncio" >next</a> |</li> <li class="right" > <a href="asyncio-api-index.html" title="High-level API Index" >previous</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.15.0a6 Documentation</a> » </li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="ipc.html" >Networking and Interprocess Communication</a> »</li> <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> »</li> <li class="nav-item nav-item-this"><a href="">Low-level API Index</a></li> <li class="right">
<div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box"> <input type="submit" value="Go"> </form> </div> | </li> <li class="right"><label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> |</li> </ul> </div> <div class="footer"> © <a href="../copyright.html">Copyright</a> 2001 Python Software Foundation. <br> This page is licensed under the Python Software Foundation License Version 2. <br> Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. <br> See <a href="/license.html">History and License</a> for more information.<br> <br>
The Python Software Foundation is a non-profit corporation.<a href="https://www.python.org/psf/donations/">Please donate.</a><br> <br> Last updated on Mar 10, 2026 (08:58 UTC). <a href="/bugs.html">Found a bug</a>? <br>
Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3. </div>
</body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450<!DOCTYPE html>
<html lang="en" data-content_root="../"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta property="og:title" content="Platform Support" /><meta property="og:type" content="website" /><meta property="og:url" content="https://docs.python.org/3/library/asyncio-platforms.html" /><meta property="og:site_name" content="Python documentation" /><meta property="og:description" content="The asyncio module is designed to be portable, but some platforms have subtle differences and limitations due to the platforms’ underlying architecture and capabilities. All Platforms: loop.add_rea..." /><meta property="og:image:width" content="1146" /><meta property="og:image:height" content="600" /><meta property="og:image" content="https://docs.python.org/3.15/_images/social_previews/summary_library_asyncio-platforms_08ee0fd4.png" /><meta property="og:image:alt" content="The asyncio module is designed to be portable, but some platforms have subtle differences and limitations due to the platforms’ underlying architecture and capabilities. All Platforms: loop.add_rea..." /><meta name="description" content="The asyncio module is designed to be portable, but some platforms have subtle differences and limitations due to the platforms’ underlying architecture and capabilities. All Platforms: loop.add_rea..." /><meta name="twitter:card" content="summary_large_image" /><meta name="theme-color" content="#3776ab">
<title>Platform Support — Python 3.15.0a6 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" /> <link rel="stylesheet" type="text/css" href="../_static/classic.css?v=234b1a7c" /> <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=89a2f22a" /> <link rel="stylesheet" type="text/css" href="../_static/profiling-sampling-visualization.css?v=0c2600ae" /> <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" /> <script src="../_static/documentation_options.js?v=6b7c9ff5"></script> <script src="../_static/doctools.js?v=9bcbadda"></script> <script src="../_static/sphinx_highlight.js?v=dc90522c"></script> <script src="../_static/profiling-sampling-visualization.js?v=9811ed04"></script> <script src="../_static/sidebar.js"></script> <link rel="search" type="application/opensearchdescription+xml" title="Search within Python 3.15.0a6 documentation" href="../_static/opensearch.xml"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="copyright" title="Copyright" href="../copyright.html" /> <link rel="next" title="Extending" href="asyncio-extending.html" /> <link rel="prev" title="Policies" href="asyncio-policy.html" /> <script defer file-types="bz2,epub,zip" data-domain="docs.python.org" src="https://analytics.python.org/js/script.file-downloads.outbound-links.js"></script> <link rel="canonical" href="https://docs.python.org/3/library/asyncio-platforms.html">
<style> @media only screen { table.full-width-table { width: 100%; } } </style><link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css"> <link rel="shortcut icon" type="image/png" href="../_static/py.svg"> <script type="text/javascript" src="../_static/copybutton.js"></script> <script type="text/javascript" src="../_static/menu.js"></script> <script type="text/javascript" src="../_static/search-focus.js"></script> <script type="text/javascript" src="../_static/themetoggle.js"></script> <script type="text/javascript" src="../_static/rtd_switcher.js"></script> <meta name="readthedocs-addons-api-version" content="1">
</head><body><div class="mobile-nav"> <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation" aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu"> <nav class="nav-content" role="navigation"> <label for="menuToggler" class="toggler__label"> <span></span> </label> <span class="nav-items-wrapper"> <a href="https://www.python.org/" class="nav-logo"> <img src="../_static/py.svg" alt="Python logo"> </a> <span class="version_switcher_placeholder"></span> <form role="search" class="search" action="../search.html" method="get"> <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon"> <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> </svg> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q"> <input type="submit" value="Go"> </form> </span> </nav> <div class="menu-wrapper"> <nav class="menu" role="navigation" aria-label="main navigation"> <div class="language_switcher_placeholder"></div> <label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> <div> <h3><a href="../contents.html">Table of Contents</a></h3> <ul><li><a class="reference internal" href="#">Platform Support</a><ul><li><a class="reference internal" href="#all-platforms">All Platforms</a></li><li><a class="reference internal" href="#windows">Windows</a><ul><li><a class="reference internal" href="#subprocess-support-on-windows">Subprocess Support on Windows</a></li></ul></li><li><a class="reference internal" href="#macos">macOS</a></li></ul></li></ul>
</div> <div> <h4>Previous topic</h4> <p class="topless"><a href="asyncio-policy.html" title="previous chapter">Policies</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="asyncio-extending.html" title="next chapter">Extending</a></p> </div> <script> document.addEventListener('DOMContentLoaded', () => { const title = document.querySelector('meta[property="og:title"]').content; const elements = document.querySelectorAll('.improvepage'); const pageurl = window.location.href.split('?')[0]; elements.forEach(element => { const url = new URL(element.href.split('?')[0].replace("-nojs", "")); url.searchParams.set('pagetitle', title); url.searchParams.set('pageurl', pageurl); url.searchParams.set('pagesource', "library/asyncio-platforms.rst"); element.href = url.toString(); }); }); </script> <div role="note" aria-label="source link"> <h3>This page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a bug</a></li> <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li> <li> <a href="https://github.com/python/cpython/blob/main/Doc/library/asyncio-platforms.rst?plain=1" rel="nofollow">Show source </a> </li> </ul> </div> </nav> </div></div>
<div class="related" role="navigation" aria-label="Related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="asyncio-extending.html" title="Extending" accesskey="N">next</a> |</li> <li class="right" > <a href="asyncio-policy.html" title="Policies" accesskey="P">previous</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.15.0a6 Documentation</a> » </li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="ipc.html" >Networking and Interprocess Communication</a> »</li> <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> »</li> <li class="nav-item nav-item-this"><a href="">Platform Support</a></li> <li class="right">
<div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box"> <input type="submit" value="Go"> </form> </div> | </li> <li class="right"><label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> |</li> </ul> </div>
<div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <section id="platform-support"><span id="asyncio-platform-support"></span><h1>Platform Support<a class="headerlink" href="#platform-support" title="Link to this heading">¶</a></h1><p>The <a class="reference internal" href="asyncio.html#module-asyncio" title="asyncio: Asynchronous I/O."><code class="xref py py-mod docutils literal notranslate"><span class="pre">asyncio</span></code></a> module is designed to be portable,but some platforms have subtle differences and limitationsdue to the platforms’ underlying architecture and capabilities.</p><section id="all-platforms"><h2>All Platforms<a class="headerlink" href="#all-platforms" title="Link to this heading">¶</a></h2><ul class="simple"><li><p><a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.add_reader" title="asyncio.loop.add_reader"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.add_reader()</span></code></a> and <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.add_writer" title="asyncio.loop.add_writer"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.add_writer()</span></code></a>cannot be used to monitor file I/O.</p></li></ul></section><section id="windows"><h2>Windows<a class="headerlink" href="#windows" title="Link to this heading">¶</a></h2><p><strong>Source code:</strong> <a class="extlink-source reference external" href="https://github.com/python/cpython/tree/main/Lib/asyncio/proactor_events.py">Lib/asyncio/proactor_events.py</a>,<a class="extlink-source reference external" href="https://github.com/python/cpython/tree/main/Lib/asyncio/windows_events.py">Lib/asyncio/windows_events.py</a>,<a class="extlink-source reference external" href="https://github.com/python/cpython/tree/main/Lib/asyncio/windows_utils.py">Lib/asyncio/windows_utils.py</a></p><hr class="docutils" /><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.8: </span>On Windows, <a class="reference internal" href="asyncio-eventloop.html#asyncio.ProactorEventLoop" title="asyncio.ProactorEventLoop"><code class="xref py py-class docutils literal notranslate"><span class="pre">ProactorEventLoop</span></code></a> is now the default event loop.</p></div><p>All event loops on Windows do not support the following methods:</p><ul class="simple"><li><p><a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.create_unix_connection" title="asyncio.loop.create_unix_connection"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.create_unix_connection()</span></code></a> and<a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.create_unix_server" title="asyncio.loop.create_unix_server"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.create_unix_server()</span></code></a> are not supported.The <a class="reference internal" href="socket.html#socket.AF_UNIX" title="socket.AF_UNIX"><code class="xref py py-const docutils literal notranslate"><span class="pre">socket.AF_UNIX</span></code></a> socket family is specific to Unix.</p></li><li><p><a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.add_signal_handler" title="asyncio.loop.add_signal_handler"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.add_signal_handler()</span></code></a> and<a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.remove_signal_handler" title="asyncio.loop.remove_signal_handler"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.remove_signal_handler()</span></code></a> are not supported.</p></li></ul><p><a class="reference internal" href="asyncio-eventloop.html#asyncio.SelectorEventLoop" title="asyncio.SelectorEventLoop"><code class="xref py py-class docutils literal notranslate"><span class="pre">SelectorEventLoop</span></code></a> has the following limitations:</p><ul class="simple"><li><p><a class="reference internal" href="selectors.html#selectors.SelectSelector" title="selectors.SelectSelector"><code class="xref py py-class docutils literal notranslate"><span class="pre">SelectSelector</span></code></a> is used to wait on socket events:it supports sockets and is limited to 512 sockets.</p></li><li><p><a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.add_reader" title="asyncio.loop.add_reader"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.add_reader()</span></code></a> and <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.add_writer" title="asyncio.loop.add_writer"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.add_writer()</span></code></a> only acceptsocket handles (e.g. pipe file descriptors are not supported).</p></li><li><p>Pipes are not supported, so the <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.connect_read_pipe" title="asyncio.loop.connect_read_pipe"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.connect_read_pipe()</span></code></a>and <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.connect_write_pipe" title="asyncio.loop.connect_write_pipe"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.connect_write_pipe()</span></code></a> methods are not implemented.</p></li><li><p><a class="reference internal" href="asyncio-subprocess.html#asyncio-subprocess"><span class="std std-ref">Subprocesses</span></a> are not supported, i.e.<a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.subprocess_exec" title="asyncio.loop.subprocess_exec"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.subprocess_exec()</span></code></a> and <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.subprocess_shell" title="asyncio.loop.subprocess_shell"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.subprocess_shell()</span></code></a>methods are not implemented.</p></li></ul><p><a class="reference internal" href="asyncio-eventloop.html#asyncio.ProactorEventLoop" title="asyncio.ProactorEventLoop"><code class="xref py py-class docutils literal notranslate"><span class="pre">ProactorEventLoop</span></code></a> has the following limitations:</p><ul class="simple"><li><p>The <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.add_reader" title="asyncio.loop.add_reader"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.add_reader()</span></code></a> and <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.add_writer" title="asyncio.loop.add_writer"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.add_writer()</span></code></a>methods are not supported.</p></li></ul><p>The resolution of the monotonic clock on Windows is usually around 15.6milliseconds. The best resolution is 0.5 milliseconds. The resolution depends on thehardware (availability of <a class="reference external" href="https://en.wikipedia.org/wiki/High_Precision_Event_Timer">HPET</a>) and on theWindows configuration.</p><section id="subprocess-support-on-windows"><span id="asyncio-windows-subprocess"></span><h3>Subprocess Support on Windows<a class="headerlink" href="#subprocess-support-on-windows" title="Link to this heading">¶</a></h3><p>On Windows, the default event loop <a class="reference internal" href="asyncio-eventloop.html#asyncio.ProactorEventLoop" title="asyncio.ProactorEventLoop"><code class="xref py py-class docutils literal notranslate"><span class="pre">ProactorEventLoop</span></code></a> supportssubprocesses, whereas <a class="reference internal" href="asyncio-eventloop.html#asyncio.SelectorEventLoop" title="asyncio.SelectorEventLoop"><code class="xref py py-class docutils literal notranslate"><span class="pre">SelectorEventLoop</span></code></a> does not.</p></section></section><section id="macos"><h2>macOS<a class="headerlink" href="#macos" title="Link to this heading">¶</a></h2><p>Modern macOS versions are fully supported.</p><p class="rubric">macOS <= 10.8</p><p>On macOS 10.6, 10.7 and 10.8, the default event loopuses <a class="reference internal" href="selectors.html#selectors.KqueueSelector" title="selectors.KqueueSelector"><code class="xref py py-class docutils literal notranslate"><span class="pre">selectors.KqueueSelector</span></code></a>, which does not supportcharacter devices on these versions. The <a class="reference internal" href="asyncio-eventloop.html#asyncio.SelectorEventLoop" title="asyncio.SelectorEventLoop"><code class="xref py py-class docutils literal notranslate"><span class="pre">SelectorEventLoop</span></code></a>can be manually configured to use <a class="reference internal" href="selectors.html#selectors.SelectSelector" title="selectors.SelectSelector"><code class="xref py py-class docutils literal notranslate"><span class="pre">SelectSelector</span></code></a>or <a class="reference internal" href="selectors.html#selectors.PollSelector" title="selectors.PollSelector"><code class="xref py py-class docutils literal notranslate"><span class="pre">PollSelector</span></code></a> to support character devices onthese older versions of macOS. Example:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span><span class="w"> </span><span class="nn">asyncio</span><span class="kn">import</span><span class="w"> </span><span class="nn">selectors</span>
<span class="n">selector</span> <span class="o">=</span> <span class="n">selectors</span><span class="o">.</span><span class="n">SelectSelector</span><span class="p">()</span><span class="n">loop</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">SelectorEventLoop</span><span class="p">(</span><span class="n">selector</span><span class="p">)</span><span class="n">asyncio</span><span class="o">.</span><span class="n">set_event_loop</span><span class="p">(</span><span class="n">loop</span><span class="p">)</span></pre></div></div></section></section>
<div class="clearer"></div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="Main"> <div class="sphinxsidebarwrapper"> <div> <h3><a href="../contents.html">Table of Contents</a></h3> <ul><li><a class="reference internal" href="#">Platform Support</a><ul><li><a class="reference internal" href="#all-platforms">All Platforms</a></li><li><a class="reference internal" href="#windows">Windows</a><ul><li><a class="reference internal" href="#subprocess-support-on-windows">Subprocess Support on Windows</a></li></ul></li><li><a class="reference internal" href="#macos">macOS</a></li></ul></li></ul>
</div> <div> <h4>Previous topic</h4> <p class="topless"><a href="asyncio-policy.html" title="previous chapter">Policies</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="asyncio-extending.html" title="next chapter">Extending</a></p> </div> <script> document.addEventListener('DOMContentLoaded', () => { const title = document.querySelector('meta[property="og:title"]').content; const elements = document.querySelectorAll('.improvepage'); const pageurl = window.location.href.split('?')[0]; elements.forEach(element => { const url = new URL(element.href.split('?')[0].replace("-nojs", "")); url.searchParams.set('pagetitle', title); url.searchParams.set('pageurl', pageurl); url.searchParams.set('pagesource', "library/asyncio-platforms.rst"); element.href = url.toString(); }); }); </script> <div role="note" aria-label="source link"> <h3>This page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a bug</a></li> <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li> <li> <a href="https://github.com/python/cpython/blob/main/Doc/library/asyncio-platforms.rst?plain=1" rel="nofollow">Show source </a> </li> </ul> </div> </div><div id="sidebarbutton" title="Collapse sidebar"><span>«</span></div>
</div> <div class="clearer"></div> </div> <div class="related" role="navigation" aria-label="Related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="asyncio-extending.html" title="Extending" >next</a> |</li> <li class="right" > <a href="asyncio-policy.html" title="Policies" >previous</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.15.0a6 Documentation</a> » </li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="ipc.html" >Networking and Interprocess Communication</a> »</li> <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> »</li> <li class="nav-item nav-item-this"><a href="">Platform Support</a></li> <li class="right">
<div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box"> <input type="submit" value="Go"> </form> </div> | </li> <li class="right"><label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> |</li> </ul> </div> <div class="footer"> © <a href="../copyright.html">Copyright</a> 2001 Python Software Foundation. <br> This page is licensed under the Python Software Foundation License Version 2. <br> Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. <br> See <a href="/license.html">History and License</a> for more information.<br> <br>
The Python Software Foundation is a non-profit corporation.<a href="https://www.python.org/psf/donations/">Please donate.</a><br> <br> Last updated on Mar 10, 2026 (08:58 UTC). <a href="/bugs.html">Found a bug</a>? <br>
Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3. </div>
</body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528<!DOCTYPE html>
<html lang="en" data-content_root="../"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta property="og:title" content="Policies" /><meta property="og:type" content="website" /><meta property="og:url" content="https://docs.python.org/3/library/asyncio-policy.html" /><meta property="og:site_name" content="Python documentation" /><meta property="og:description" content="An event loop policy is a global object used to get and set the current event loop, as well as create new event loops. The default policy can be replaced with built-in alternatives to use different..." /><meta property="og:image:width" content="1146" /><meta property="og:image:height" content="600" /><meta property="og:image" content="https://docs.python.org/3.15/_images/social_previews/summary_library_asyncio-policy_7192a5d0.png" /><meta property="og:image:alt" content="An event loop policy is a global object used to get and set the current event loop, as well as create new event loops. The default policy can be replaced with built-in alternatives to use different..." /><meta name="description" content="An event loop policy is a global object used to get and set the current event loop, as well as create new event loops. The default policy can be replaced with built-in alternatives to use different..." /><meta name="twitter:card" content="summary_large_image" /><meta name="theme-color" content="#3776ab">
<title>Policies — Python 3.15.0a6 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" /> <link rel="stylesheet" type="text/css" href="../_static/classic.css?v=234b1a7c" /> <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=89a2f22a" /> <link rel="stylesheet" type="text/css" href="../_static/profiling-sampling-visualization.css?v=0c2600ae" /> <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" /> <script src="../_static/documentation_options.js?v=6b7c9ff5"></script> <script src="../_static/doctools.js?v=9bcbadda"></script> <script src="../_static/sphinx_highlight.js?v=dc90522c"></script> <script src="../_static/profiling-sampling-visualization.js?v=9811ed04"></script> <script src="../_static/sidebar.js"></script> <link rel="search" type="application/opensearchdescription+xml" title="Search within Python 3.15.0a6 documentation" href="../_static/opensearch.xml"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="copyright" title="Copyright" href="../copyright.html" /> <link rel="next" title="Platform Support" href="asyncio-platforms.html" /> <link rel="prev" title="Transports and Protocols" href="asyncio-protocol.html" /> <script defer file-types="bz2,epub,zip" data-domain="docs.python.org" src="https://analytics.python.org/js/script.file-downloads.outbound-links.js"></script> <link rel="canonical" href="https://docs.python.org/3/library/asyncio-policy.html">
<style> @media only screen { table.full-width-table { width: 100%; } } </style><link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css"> <link rel="shortcut icon" type="image/png" href="../_static/py.svg"> <script type="text/javascript" src="../_static/copybutton.js"></script> <script type="text/javascript" src="../_static/menu.js"></script> <script type="text/javascript" src="../_static/search-focus.js"></script> <script type="text/javascript" src="../_static/themetoggle.js"></script> <script type="text/javascript" src="../_static/rtd_switcher.js"></script> <meta name="readthedocs-addons-api-version" content="1">
</head><body><div class="mobile-nav"> <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation" aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu"> <nav class="nav-content" role="navigation"> <label for="menuToggler" class="toggler__label"> <span></span> </label> <span class="nav-items-wrapper"> <a href="https://www.python.org/" class="nav-logo"> <img src="../_static/py.svg" alt="Python logo"> </a> <span class="version_switcher_placeholder"></span> <form role="search" class="search" action="../search.html" method="get"> <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon"> <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> </svg> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q"> <input type="submit" value="Go"> </form> </span> </nav> <div class="menu-wrapper"> <nav class="menu" role="navigation" aria-label="main navigation"> <div class="language_switcher_placeholder"></div> <label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> <div> <h3><a href="../contents.html">Table of Contents</a></h3> <ul><li><a class="reference internal" href="#">Policies</a><ul><li><a class="reference internal" href="#getting-and-setting-the-policy">Getting and Setting the Policy</a></li><li><a class="reference internal" href="#policy-objects">Policy Objects</a></li><li><a class="reference internal" href="#custom-policies">Custom Policies</a></li></ul></li></ul>
</div> <div> <h4>Previous topic</h4> <p class="topless"><a href="asyncio-protocol.html" title="previous chapter">Transports and Protocols</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="asyncio-platforms.html" title="next chapter">Platform Support</a></p> </div> <script> document.addEventListener('DOMContentLoaded', () => { const title = document.querySelector('meta[property="og:title"]').content; const elements = document.querySelectorAll('.improvepage'); const pageurl = window.location.href.split('?')[0]; elements.forEach(element => { const url = new URL(element.href.split('?')[0].replace("-nojs", "")); url.searchParams.set('pagetitle', title); url.searchParams.set('pageurl', pageurl); url.searchParams.set('pagesource', "library/asyncio-policy.rst"); element.href = url.toString(); }); }); </script> <div role="note" aria-label="source link"> <h3>This page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a bug</a></li> <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li> <li> <a href="https://github.com/python/cpython/blob/main/Doc/library/asyncio-policy.rst?plain=1" rel="nofollow">Show source </a> </li> </ul> </div> </nav> </div></div>
<div class="related" role="navigation" aria-label="Related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="asyncio-platforms.html" title="Platform Support" accesskey="N">next</a> |</li> <li class="right" > <a href="asyncio-protocol.html" title="Transports and Protocols" accesskey="P">previous</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.15.0a6 Documentation</a> » </li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="ipc.html" >Networking and Interprocess Communication</a> »</li> <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> »</li> <li class="nav-item nav-item-this"><a href="">Policies</a></li> <li class="right">
<div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box"> <input type="submit" value="Go"> </form> </div> | </li> <li class="right"><label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> |</li> </ul> </div>
<div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <section id="policies"><span id="asyncio-policies"></span><h1>Policies<a class="headerlink" href="#policies" title="Link to this heading">¶</a></h1><div class="admonition warning"><p class="admonition-title">Warning</p><p>Policies are deprecated and will be removed in Python 3.16.Users are encouraged to use 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> functionor the <a class="reference internal" href="asyncio-runner.html#asyncio.Runner" title="asyncio.Runner"><code class="xref py py-class docutils literal notranslate"><span class="pre">asyncio.Runner</span></code></a> with <em>loop_factory</em> to usethe desired loop implementation.</p></div><p>An event loop policy is a global objectused to get and set the current <a class="reference internal" href="asyncio-eventloop.html#asyncio-event-loop"><span class="std std-ref">event loop</span></a>,as well as create new event loops.The default policy can be <a class="reference internal" href="#asyncio-policy-get-set"><span class="std std-ref">replaced</span></a> with<a class="reference internal" href="#asyncio-policy-builtin"><span class="std std-ref">built-in alternatives</span></a>to use different event loop implementations,or substituted by a <a class="reference internal" href="#asyncio-custom-policies"><span class="std std-ref">custom policy</span></a>that can override these behaviors.</p><p>The <a class="reference internal" href="#asyncio-policy-objects"><span class="std std-ref">policy object</span></a>gets and sets a separate event loop per <em>context</em>.This is per-thread by default,though custom policies could define <em>context</em> differently.</p><p>Custom event loop policies can control the behavior of<a class="reference internal" href="asyncio-eventloop.html#asyncio.get_event_loop" title="asyncio.get_event_loop"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_event_loop()</span></code></a>, <a class="reference internal" href="asyncio-eventloop.html#asyncio.set_event_loop" title="asyncio.set_event_loop"><code class="xref py py-func docutils literal notranslate"><span class="pre">set_event_loop()</span></code></a>, and <a class="reference internal" href="asyncio-eventloop.html#asyncio.new_event_loop" title="asyncio.new_event_loop"><code class="xref py py-func docutils literal notranslate"><span class="pre">new_event_loop()</span></code></a>.</p><p>Policy objects should implement the APIs definedin the <a class="reference internal" href="#asyncio.AbstractEventLoopPolicy" title="asyncio.AbstractEventLoopPolicy"><code class="xref py py-class docutils literal notranslate"><span class="pre">AbstractEventLoopPolicy</span></code></a> abstract base class.</p><section id="getting-and-setting-the-policy"><span id="asyncio-policy-get-set"></span><h2>Getting and Setting the Policy<a class="headerlink" href="#getting-and-setting-the-policy" title="Link to this heading">¶</a></h2><p>The following functions can be used to get and set the policyfor the current process:</p><dl class="py function"><dt class="sig sig-object py" id="asyncio.get_event_loop_policy"><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">get_event_loop_policy</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.get_event_loop_policy" title="Link to this definition">¶</a></dt><dd><p>Return the current process-wide policy.</p><div class="deprecated"><p><span class="versionmodified deprecated">Deprecated since version 3.14: </span>The <code class="xref py py-func docutils literal notranslate"><span class="pre">get_event_loop_policy()</span></code> function is deprecated andwill be removed in Python 3.16.</p></div></dd></dl>
<dl class="py function"><dt class="sig sig-object py" id="asyncio.set_event_loop_policy"><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">set_event_loop_policy</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">policy</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.set_event_loop_policy" title="Link to this definition">¶</a></dt><dd><p>Set the current process-wide policy to <em>policy</em>.</p><p>If <em>policy</em> is set to <code class="docutils literal notranslate"><span class="pre">None</span></code>, the default policy is restored.</p><div class="deprecated"><p><span class="versionmodified deprecated">Deprecated since version 3.14: </span>The <code class="xref py py-func docutils literal notranslate"><span class="pre">set_event_loop_policy()</span></code> function is deprecated andwill be removed in Python 3.16.</p></div></dd></dl>
</section><section id="policy-objects"><span id="asyncio-policy-objects"></span><h2>Policy Objects<a class="headerlink" href="#policy-objects" title="Link to this heading">¶</a></h2><p>The abstract event loop policy base class is defined as follows:</p><dl class="py class"><dt class="sig sig-object py" id="asyncio.AbstractEventLoopPolicy"><em class="property"><span class="k"><span class="pre">class</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">AbstractEventLoopPolicy</span></span><a class="headerlink" href="#asyncio.AbstractEventLoopPolicy" title="Link to this definition">¶</a></dt><dd><p>An abstract base class for asyncio policies.</p><dl class="py method"><dt class="sig sig-object py" id="asyncio.AbstractEventLoopPolicy.get_event_loop"><span class="sig-name descname"><span class="pre">get_event_loop</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.AbstractEventLoopPolicy.get_event_loop" title="Link to this definition">¶</a></dt><dd><p>Get the event loop for the current context.</p><p>Return an event loop object implementing the<a class="reference internal" href="asyncio-eventloop.html#asyncio.AbstractEventLoop" title="asyncio.AbstractEventLoop"><code class="xref py py-class docutils literal notranslate"><span class="pre">AbstractEventLoop</span></code></a> interface.</p><p>This method should never return <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.6.</span></p></div></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.AbstractEventLoopPolicy.set_event_loop"><span class="sig-name descname"><span class="pre">set_event_loop</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">loop</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.AbstractEventLoopPolicy.set_event_loop" title="Link to this definition">¶</a></dt><dd><p>Set the event loop for the current context to <em>loop</em>.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.AbstractEventLoopPolicy.new_event_loop"><span class="sig-name descname"><span class="pre">new_event_loop</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.AbstractEventLoopPolicy.new_event_loop" title="Link to this definition">¶</a></dt><dd><p>Create and return a new event loop object.</p><p>This method should never return <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p></dd></dl>
<div class="deprecated"><p><span class="versionmodified deprecated">Deprecated since version 3.14: </span>The <code class="xref py py-class docutils literal notranslate"><span class="pre">AbstractEventLoopPolicy</span></code> class is deprecated andwill be removed in Python 3.16.</p></div></dd></dl>
<p id="asyncio-policy-builtin">asyncio ships with the following built-in policies:</p><dl class="py class"><dt class="sig sig-object py" id="asyncio.DefaultEventLoopPolicy"><em class="property"><span class="k"><span class="pre">class</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">DefaultEventLoopPolicy</span></span><a class="headerlink" href="#asyncio.DefaultEventLoopPolicy" title="Link to this definition">¶</a></dt><dd><p>The default asyncio policy. Uses <a class="reference internal" href="asyncio-eventloop.html#asyncio.SelectorEventLoop" title="asyncio.SelectorEventLoop"><code class="xref py py-class docutils literal notranslate"><span class="pre">SelectorEventLoop</span></code></a>on Unix and <a class="reference internal" href="asyncio-eventloop.html#asyncio.ProactorEventLoop" title="asyncio.ProactorEventLoop"><code class="xref py py-class docutils literal notranslate"><span class="pre">ProactorEventLoop</span></code></a> on Windows.</p><p>There is no need to install the default policy manually. asynciois configured to use the default policy automatically.</p><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.8: </span>On Windows, <a class="reference internal" href="asyncio-eventloop.html#asyncio.ProactorEventLoop" title="asyncio.ProactorEventLoop"><code class="xref py py-class docutils literal notranslate"><span class="pre">ProactorEventLoop</span></code></a> is now used by default.</p></div><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.14: </span>The <a class="reference internal" href="asyncio-eventloop.html#asyncio.get_event_loop" title="asyncio.get_event_loop"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_event_loop()</span></code></a> method of the default asyncio policy nowraises a <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> if there is no set event loop.</p></div><div class="deprecated"><p><span class="versionmodified deprecated">Deprecated since version 3.14: </span>The <code class="xref py py-class docutils literal notranslate"><span class="pre">DefaultEventLoopPolicy</span></code> class is deprecated andwill be removed in Python 3.16.</p></div></dd></dl>
<dl class="py class"><dt class="sig sig-object py" id="asyncio.WindowsSelectorEventLoopPolicy"><em class="property"><span class="k"><span class="pre">class</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">WindowsSelectorEventLoopPolicy</span></span><a class="headerlink" href="#asyncio.WindowsSelectorEventLoopPolicy" title="Link to this definition">¶</a></dt><dd><p>An alternative event loop policy that uses the<a class="reference internal" href="asyncio-eventloop.html#asyncio.SelectorEventLoop" title="asyncio.SelectorEventLoop"><code class="xref py py-class docutils literal notranslate"><span class="pre">SelectorEventLoop</span></code></a> event loop implementation.</p><div class="availability docutils container"><p><a class="reference internal" href="intro.html#availability"><span class="std std-ref">Availability</span></a>: Windows.</p></div><div class="deprecated"><p><span class="versionmodified deprecated">Deprecated since version 3.14: </span>The <code class="xref py py-class docutils literal notranslate"><span class="pre">WindowsSelectorEventLoopPolicy</span></code> class is deprecated andwill be removed in Python 3.16.</p></div></dd></dl>
<dl class="py class"><dt class="sig sig-object py" id="asyncio.WindowsProactorEventLoopPolicy"><em class="property"><span class="k"><span class="pre">class</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">WindowsProactorEventLoopPolicy</span></span><a class="headerlink" href="#asyncio.WindowsProactorEventLoopPolicy" title="Link to this definition">¶</a></dt><dd><p>An alternative event loop policy that uses the<a class="reference internal" href="asyncio-eventloop.html#asyncio.ProactorEventLoop" title="asyncio.ProactorEventLoop"><code class="xref py py-class docutils literal notranslate"><span class="pre">ProactorEventLoop</span></code></a> event loop implementation.</p><div class="availability docutils container"><p><a class="reference internal" href="intro.html#availability"><span class="std std-ref">Availability</span></a>: Windows.</p></div><div class="deprecated"><p><span class="versionmodified deprecated">Deprecated since version 3.14: </span>The <code class="xref py py-class docutils literal notranslate"><span class="pre">WindowsProactorEventLoopPolicy</span></code> class is deprecated andwill be removed in Python 3.16.</p></div></dd></dl>
</section><section id="custom-policies"><span id="asyncio-custom-policies"></span><h2>Custom Policies<a class="headerlink" href="#custom-policies" title="Link to this heading">¶</a></h2><p>To implement a new event loop policy, it is recommended to subclass<a class="reference internal" href="#asyncio.DefaultEventLoopPolicy" title="asyncio.DefaultEventLoopPolicy"><code class="xref py py-class docutils literal notranslate"><span class="pre">DefaultEventLoopPolicy</span></code></a> and override the methods for whichcustom behavior is wanted, e.g.:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span><span class="w"> </span><span class="nc">MyEventLoopPolicy</span><span class="p">(</span><span class="n">asyncio</span><span class="o">.</span><span class="n">DefaultEventLoopPolicy</span><span class="p">):</span>
<span class="k">def</span><span class="w"> </span><span class="nf">get_event_loop</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span><span class="w"> </span><span class="sd">"""Get the event loop.</span>
<span class="sd"> This may be None or an instance of EventLoop.</span><span class="sd"> """</span> <span class="n">loop</span> <span class="o">=</span> <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="n">get_event_loop</span><span class="p">()</span> <span class="c1"># Do something with loop ...</span> <span class="k">return</span> <span class="n">loop</span>
<span class="n">asyncio</span><span class="o">.</span><span class="n">set_event_loop_policy</span><span class="p">(</span><span class="n">MyEventLoopPolicy</span><span class="p">())</span></pre></div></div></section></section>
<div class="clearer"></div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="Main"> <div class="sphinxsidebarwrapper"> <div> <h3><a href="../contents.html">Table of Contents</a></h3> <ul><li><a class="reference internal" href="#">Policies</a><ul><li><a class="reference internal" href="#getting-and-setting-the-policy">Getting and Setting the Policy</a></li><li><a class="reference internal" href="#policy-objects">Policy Objects</a></li><li><a class="reference internal" href="#custom-policies">Custom Policies</a></li></ul></li></ul>
</div> <div> <h4>Previous topic</h4> <p class="topless"><a href="asyncio-protocol.html" title="previous chapter">Transports and Protocols</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="asyncio-platforms.html" title="next chapter">Platform Support</a></p> </div> <script> document.addEventListener('DOMContentLoaded', () => { const title = document.querySelector('meta[property="og:title"]').content; const elements = document.querySelectorAll('.improvepage'); const pageurl = window.location.href.split('?')[0]; elements.forEach(element => { const url = new URL(element.href.split('?')[0].replace("-nojs", "")); url.searchParams.set('pagetitle', title); url.searchParams.set('pageurl', pageurl); url.searchParams.set('pagesource', "library/asyncio-policy.rst"); element.href = url.toString(); }); }); </script> <div role="note" aria-label="source link"> <h3>This page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a bug</a></li> <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li> <li> <a href="https://github.com/python/cpython/blob/main/Doc/library/asyncio-policy.rst?plain=1" rel="nofollow">Show source </a> </li> </ul> </div> </div><div id="sidebarbutton" title="Collapse sidebar"><span>«</span></div>
</div> <div class="clearer"></div> </div> <div class="related" role="navigation" aria-label="Related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="asyncio-platforms.html" title="Platform Support" >next</a> |</li> <li class="right" > <a href="asyncio-protocol.html" title="Transports and Protocols" >previous</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.15.0a6 Documentation</a> » </li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="ipc.html" >Networking and Interprocess Communication</a> »</li> <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> »</li> <li class="nav-item nav-item-this"><a href="">Policies</a></li> <li class="right">
<div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box"> <input type="submit" value="Go"> </form> </div> | </li> <li class="right"><label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> |</li> </ul> </div> <div class="footer"> © <a href="../copyright.html">Copyright</a> 2001 Python Software Foundation. <br> This page is licensed under the Python Software Foundation License Version 2. <br> Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. <br> See <a href="/license.html">History and License</a> for more information.<br> <br>
The Python Software Foundation is a non-profit corporation.<a href="https://www.python.org/psf/donations/">Please donate.</a><br> <br> Last updated on Mar 10, 2026 (08:58 UTC). <a href="/bugs.html">Found a bug</a>? <br>
Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3. </div>
</body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626<!DOCTYPE html>
<html lang="en" data-content_root="../"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta property="og:title" content="Queues" /><meta property="og:type" content="website" /><meta property="og:url" content="https://docs.python.org/3/library/asyncio-queue.html" /><meta property="og:site_name" content="Python documentation" /><meta property="og:description" content="Source code: Lib/asyncio/queues.py asyncio queues are designed to be similar to classes of the queue module. Although asyncio queues are not thread-safe, they are designed to be used specifically i..." /><meta property="og:image:width" content="1146" /><meta property="og:image:height" content="600" /><meta property="og:image" content="https://docs.python.org/3.15/_images/social_previews/summary_library_asyncio-queue_26850ff4.png" /><meta property="og:image:alt" content="Source code: Lib/asyncio/queues.py asyncio queues are designed to be similar to classes of the queue module. Although asyncio queues are not thread-safe, they are designed to be used specifically i..." /><meta name="description" content="Source code: Lib/asyncio/queues.py asyncio queues are designed to be similar to classes of the queue module. Although asyncio queues are not thread-safe, they are designed to be used specifically i..." /><meta name="twitter:card" content="summary_large_image" /><meta name="theme-color" content="#3776ab">
<title>Queues — Python 3.15.0a6 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" /> <link rel="stylesheet" type="text/css" href="../_static/classic.css?v=234b1a7c" /> <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=89a2f22a" /> <link rel="stylesheet" type="text/css" href="../_static/profiling-sampling-visualization.css?v=0c2600ae" /> <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" /> <script src="../_static/documentation_options.js?v=6b7c9ff5"></script> <script src="../_static/doctools.js?v=9bcbadda"></script> <script src="../_static/sphinx_highlight.js?v=dc90522c"></script> <script src="../_static/profiling-sampling-visualization.js?v=9811ed04"></script> <script src="../_static/sidebar.js"></script> <link rel="search" type="application/opensearchdescription+xml" title="Search within Python 3.15.0a6 documentation" href="../_static/opensearch.xml"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="copyright" title="Copyright" href="../copyright.html" /> <link rel="next" title="Exceptions" href="asyncio-exceptions.html" /> <link rel="prev" title="Subprocesses" href="asyncio-subprocess.html" /> <script defer file-types="bz2,epub,zip" data-domain="docs.python.org" src="https://analytics.python.org/js/script.file-downloads.outbound-links.js"></script> <link rel="canonical" href="https://docs.python.org/3/library/asyncio-queue.html">
<style> @media only screen { table.full-width-table { width: 100%; } } </style><link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css"> <link rel="shortcut icon" type="image/png" href="../_static/py.svg"> <script type="text/javascript" src="../_static/copybutton.js"></script> <script type="text/javascript" src="../_static/menu.js"></script> <script type="text/javascript" src="../_static/search-focus.js"></script> <script type="text/javascript" src="../_static/themetoggle.js"></script> <script type="text/javascript" src="../_static/rtd_switcher.js"></script> <meta name="readthedocs-addons-api-version" content="1">
</head><body><div class="mobile-nav"> <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation" aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu"> <nav class="nav-content" role="navigation"> <label for="menuToggler" class="toggler__label"> <span></span> </label> <span class="nav-items-wrapper"> <a href="https://www.python.org/" class="nav-logo"> <img src="../_static/py.svg" alt="Python logo"> </a> <span class="version_switcher_placeholder"></span> <form role="search" class="search" action="../search.html" method="get"> <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon"> <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> </svg> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q"> <input type="submit" value="Go"> </form> </span> </nav> <div class="menu-wrapper"> <nav class="menu" role="navigation" aria-label="main navigation"> <div class="language_switcher_placeholder"></div> <label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> <div> <h3><a href="../contents.html">Table of Contents</a></h3> <ul><li><a class="reference internal" href="#">Queues</a><ul><li><a class="reference internal" href="#queue">Queue</a></li><li><a class="reference internal" href="#priority-queue">Priority Queue</a></li><li><a class="reference internal" href="#lifo-queue">LIFO Queue</a></li><li><a class="reference internal" href="#exceptions">Exceptions</a></li><li><a class="reference internal" href="#examples">Examples</a></li></ul></li></ul>
</div> <div> <h4>Previous topic</h4> <p class="topless"><a href="asyncio-subprocess.html" title="previous chapter">Subprocesses</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="asyncio-exceptions.html" title="next chapter">Exceptions</a></p> </div> <script> document.addEventListener('DOMContentLoaded', () => { const title = document.querySelector('meta[property="og:title"]').content; const elements = document.querySelectorAll('.improvepage'); const pageurl = window.location.href.split('?')[0]; elements.forEach(element => { const url = new URL(element.href.split('?')[0].replace("-nojs", "")); url.searchParams.set('pagetitle', title); url.searchParams.set('pageurl', pageurl); url.searchParams.set('pagesource', "library/asyncio-queue.rst"); element.href = url.toString(); }); }); </script> <div role="note" aria-label="source link"> <h3>This page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a bug</a></li> <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li> <li> <a href="https://github.com/python/cpython/blob/main/Doc/library/asyncio-queue.rst?plain=1" rel="nofollow">Show source </a> </li> </ul> </div> </nav> </div></div>
<div class="related" role="navigation" aria-label="Related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="asyncio-exceptions.html" title="Exceptions" accesskey="N">next</a> |</li> <li class="right" > <a href="asyncio-subprocess.html" title="Subprocesses" accesskey="P">previous</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.15.0a6 Documentation</a> » </li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="ipc.html" >Networking and Interprocess Communication</a> »</li> <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> »</li> <li class="nav-item nav-item-this"><a href="">Queues</a></li> <li class="right">
<div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box"> <input type="submit" value="Go"> </form> </div> | </li> <li class="right"><label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> |</li> </ul> </div>
<div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <section id="queues"><span id="asyncio-queues"></span><h1>Queues<a class="headerlink" href="#queues" title="Link to this heading">¶</a></h1><p><strong>Source code:</strong> <a class="extlink-source reference external" href="https://github.com/python/cpython/tree/main/Lib/asyncio/queues.py">Lib/asyncio/queues.py</a></p><hr class="docutils" /><p>asyncio queues are designed to be similar to classes of the<a class="reference internal" href="queue.html#module-queue" title="queue: A synchronized queue class."><code class="xref py py-mod docutils literal notranslate"><span class="pre">queue</span></code></a> module. Although asyncio queues are not thread-safe,they are designed to be used specifically in async/await code.</p><p>Note that methods of asyncio queues don’t have a <em>timeout</em> parameter;use <a class="reference internal" href="asyncio-task.html#asyncio.wait_for" title="asyncio.wait_for"><code class="xref py py-func docutils literal notranslate"><span class="pre">asyncio.wait_for()</span></code></a> function to do queue operations with atimeout.</p><p>See also the <a class="reference internal" href="#examples">Examples</a> section below.</p><section id="queue"><h2>Queue<a class="headerlink" href="#queue" title="Link to this heading">¶</a></h2><dl class="py class"><dt class="sig sig-object py" id="asyncio.Queue"><em class="property"><span class="k"><span class="pre">class</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">Queue</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">maxsize</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">0</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Queue" title="Link to this definition">¶</a></dt><dd><p>A first in, first out (FIFO) queue.</p><p>If <em>maxsize</em> is less than or equal to zero, the queue size isinfinite. If it is an integer greater than <code class="docutils literal notranslate"><span class="pre">0</span></code>, then<code class="docutils literal notranslate"><span class="pre">await</span> <span class="pre">put()</span></code> blocks when the queue reaches <em>maxsize</em>until an item is removed by <a class="reference internal" href="#asyncio.Queue.get" title="asyncio.Queue.get"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code></a>.</p><p>Unlike the standard library threading <a class="reference internal" href="queue.html#module-queue" title="queue: A synchronized queue class."><code class="xref py py-mod docutils literal notranslate"><span class="pre">queue</span></code></a>, the size ofthe queue is always known and can be returned by calling the<a class="reference internal" href="#asyncio.Queue.qsize" title="asyncio.Queue.qsize"><code class="xref py py-meth docutils literal notranslate"><span class="pre">qsize()</span></code></a> method.</p><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.10: </span>Removed the <em>loop</em> parameter.</p></div><p>This class is <a class="reference internal" href="asyncio-dev.html#asyncio-multithreading"><span class="std std-ref">not thread safe</span></a>.</p><dl class="py attribute"><dt class="sig sig-object py" id="asyncio.Queue.maxsize"><span class="sig-name descname"><span class="pre">maxsize</span></span><a class="headerlink" href="#asyncio.Queue.maxsize" title="Link to this definition">¶</a></dt><dd><p>Number of items allowed in the queue.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.Queue.empty"><span class="sig-name descname"><span class="pre">empty</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Queue.empty" title="Link to this definition">¶</a></dt><dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the queue is empty, <code class="docutils literal notranslate"><span class="pre">False</span></code> otherwise.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.Queue.full"><span class="sig-name descname"><span class="pre">full</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Queue.full" title="Link to this definition">¶</a></dt><dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if there are <a class="reference internal" href="#asyncio.Queue.maxsize" title="asyncio.Queue.maxsize"><code class="xref py py-attr docutils literal notranslate"><span class="pre">maxsize</span></code></a> items in the queue.</p><p>If the queue was initialized with <code class="docutils literal notranslate"><span class="pre">maxsize=0</span></code> (the default),then <code class="xref py py-meth docutils literal notranslate"><span class="pre">full()</span></code> never returns <code class="docutils literal notranslate"><span class="pre">True</span></code>.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.Queue.get"><em class="property"><span class="k"><span class="pre">async</span></span><span class="w"> </span></em><span class="sig-name descname"><span class="pre">get</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Queue.get" title="Link to this definition">¶</a></dt><dd><p>Remove and return an item from the queue. If queue is empty,wait until an item is available.</p><p>Raises <a class="reference internal" href="#asyncio.QueueShutDown" title="asyncio.QueueShutDown"><code class="xref py py-exc docutils literal notranslate"><span class="pre">QueueShutDown</span></code></a> if the queue has been shut down andis empty, or if the queue has been shut down immediately.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.Queue.get_nowait"><span class="sig-name descname"><span class="pre">get_nowait</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Queue.get_nowait" title="Link to this definition">¶</a></dt><dd><p>Return an item if one is immediately available, else raise<a class="reference internal" href="#asyncio.QueueEmpty" title="asyncio.QueueEmpty"><code class="xref py py-exc docutils literal notranslate"><span class="pre">QueueEmpty</span></code></a>.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.Queue.join"><em class="property"><span class="k"><span class="pre">async</span></span><span class="w"> </span></em><span class="sig-name descname"><span class="pre">join</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Queue.join" title="Link to this definition">¶</a></dt><dd><p>Block until all items in the queue have been received and processed.</p><p>The count of unfinished tasks goes up whenever an item is addedto the queue. The count goes down whenever a consumer coroutine calls<a class="reference internal" href="#asyncio.Queue.task_done" title="asyncio.Queue.task_done"><code class="xref py py-meth docutils literal notranslate"><span class="pre">task_done()</span></code></a> to indicate that the item was retrieved and allwork on it is complete. When the count of unfinished tasks dropsto zero, <code class="xref py py-meth docutils literal notranslate"><span class="pre">join()</span></code> unblocks.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.Queue.put"><em class="property"><span class="k"><span class="pre">async</span></span><span class="w"> </span></em><span class="sig-name descname"><span class="pre">put</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">item</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Queue.put" title="Link to this definition">¶</a></dt><dd><p>Put an item into the queue. If the queue is full, wait until afree slot is available before adding the item.</p><p>Raises <a class="reference internal" href="#asyncio.QueueShutDown" title="asyncio.QueueShutDown"><code class="xref py py-exc docutils literal notranslate"><span class="pre">QueueShutDown</span></code></a> if the queue has been shut down.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.Queue.put_nowait"><span class="sig-name descname"><span class="pre">put_nowait</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">item</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Queue.put_nowait" title="Link to this definition">¶</a></dt><dd><p>Put an item into the queue without blocking.</p><p>If no free slot is immediately available, raise <a class="reference internal" href="#asyncio.QueueFull" title="asyncio.QueueFull"><code class="xref py py-exc docutils literal notranslate"><span class="pre">QueueFull</span></code></a>.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.Queue.qsize"><span class="sig-name descname"><span class="pre">qsize</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Queue.qsize" title="Link to this definition">¶</a></dt><dd><p>Return the number of items in the queue.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.Queue.shutdown"><span class="sig-name descname"><span class="pre">shutdown</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">immediate</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.Queue.shutdown" title="Link to this definition">¶</a></dt><dd><p>Put a <code class="xref py py-class docutils literal notranslate"><span class="pre">Queue</span></code> instance into a shutdown mode.</p><p>The queue can no longer grow.Future calls to <a class="reference internal" href="#asyncio.Queue.put" title="asyncio.Queue.put"><code class="xref py py-meth docutils literal notranslate"><span class="pre">put()</span></code></a> raise <a class="reference internal" href="#asyncio.QueueShutDown" title="asyncio.QueueShutDown"><code class="xref py py-exc docutils literal notranslate"><span class="pre">QueueShutDown</span></code></a>.Currently blocked callers of <code class="xref py py-meth docutils literal notranslate"><span class="pre">put()</span></code> will be unblockedand will raise <code class="xref py py-exc docutils literal notranslate"><span class="pre">QueueShutDown</span></code> in the formerly awaiting task.</p><p>If <em>immediate</em> is false (the default), the queue can be wounddown normally with <a class="reference internal" href="#asyncio.Queue.get" title="asyncio.Queue.get"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code></a> calls to extract tasksthat have already been loaded.</p><p>And if <a class="reference internal" href="#asyncio.Queue.task_done" title="asyncio.Queue.task_done"><code class="xref py py-meth docutils literal notranslate"><span class="pre">task_done()</span></code></a> is called for each remaining task, apending <a class="reference internal" href="#asyncio.Queue.join" title="asyncio.Queue.join"><code class="xref py py-meth docutils literal notranslate"><span class="pre">join()</span></code></a> will be unblocked normally.</p><p>Once the queue is empty, future calls to <a class="reference internal" href="#asyncio.Queue.get" title="asyncio.Queue.get"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code></a> willraise <a class="reference internal" href="#asyncio.QueueShutDown" title="asyncio.QueueShutDown"><code class="xref py py-exc docutils literal notranslate"><span class="pre">QueueShutDown</span></code></a>.</p><p>If <em>immediate</em> is true, the queue is terminated immediately.The queue is drained to be completely empty and the countof unfinished tasks is reduced by the number of tasks drained.If unfinished tasks is zero, callers of <a class="reference internal" href="#asyncio.Queue.join" title="asyncio.Queue.join"><code class="xref py py-meth docutils literal notranslate"><span class="pre">join()</span></code></a>are unblocked. Also, blocked callers of <a class="reference internal" href="#asyncio.Queue.get" title="asyncio.Queue.get"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code></a>are unblocked and will raise <a class="reference internal" href="#asyncio.QueueShutDown" title="asyncio.QueueShutDown"><code class="xref py py-exc docutils literal notranslate"><span class="pre">QueueShutDown</span></code></a> because thequeue is empty.</p><p>Use caution when using <a class="reference internal" href="#asyncio.Queue.join" title="asyncio.Queue.join"><code class="xref py py-meth docutils literal notranslate"><span class="pre">join()</span></code></a> with <em>immediate</em> setto true. This unblocks the join even when no work has been doneon the tasks, violating the usual invariant for joining a queue.</p><div class="versionadded"><p><span class="versionmodified added">Added in version 3.13.</span></p></div></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.Queue.task_done"><span class="sig-name descname"><span class="pre">task_done</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Queue.task_done" title="Link to this definition">¶</a></dt><dd><p>Indicate that a formerly enqueued work item is complete.</p><p>Used by queue consumers. For each <a class="reference internal" href="#asyncio.Queue.get" title="asyncio.Queue.get"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code></a> used tofetch a work item, a subsequent call to <code class="xref py py-meth docutils literal notranslate"><span class="pre">task_done()</span></code> tells thequeue that the processing on the work item is complete.</p><p>If a <a class="reference internal" href="#asyncio.Queue.join" title="asyncio.Queue.join"><code class="xref py py-meth docutils literal notranslate"><span class="pre">join()</span></code></a> is currently blocking, it will resume when allitems have been processed (meaning that a <code class="xref py py-meth docutils literal notranslate"><span class="pre">task_done()</span></code>call was received for every item that had been <a class="reference internal" href="#asyncio.Queue.put" title="asyncio.Queue.put"><code class="xref py py-meth docutils literal notranslate"><span class="pre">put()</span></code></a>into the queue).</p><p>Raises <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> if called more times than there wereitems placed in the queue.</p></dd></dl>
</dd></dl>
</section><section id="priority-queue"><h2>Priority Queue<a class="headerlink" href="#priority-queue" title="Link to this heading">¶</a></h2><dl class="py class"><dt class="sig sig-object py" id="asyncio.PriorityQueue"><em class="property"><span class="k"><span class="pre">class</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">PriorityQueue</span></span><a class="headerlink" href="#asyncio.PriorityQueue" title="Link to this definition">¶</a></dt><dd><p>A variant of <a class="reference internal" href="#asyncio.Queue" title="asyncio.Queue"><code class="xref py py-class docutils literal notranslate"><span class="pre">Queue</span></code></a>; retrieves entries in priority order(lowest first).</p><p>Entries are typically tuples of the form<code class="docutils literal notranslate"><span class="pre">(priority_number,</span> <span class="pre">data)</span></code>.</p></dd></dl>
</section><section id="lifo-queue"><h2>LIFO Queue<a class="headerlink" href="#lifo-queue" title="Link to this heading">¶</a></h2><dl class="py class"><dt class="sig sig-object py" id="asyncio.LifoQueue"><em class="property"><span class="k"><span class="pre">class</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">LifoQueue</span></span><a class="headerlink" href="#asyncio.LifoQueue" title="Link to this definition">¶</a></dt><dd><p>A variant of <a class="reference internal" href="#asyncio.Queue" title="asyncio.Queue"><code class="xref py py-class docutils literal notranslate"><span class="pre">Queue</span></code></a> that retrieves most recently addedentries first (last in, first out).</p></dd></dl>
</section><section id="exceptions"><h2>Exceptions<a class="headerlink" href="#exceptions" title="Link to this heading">¶</a></h2><dl class="py exception"><dt class="sig sig-object py" id="asyncio.QueueEmpty"><em class="property"><span class="k"><span class="pre">exception</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">QueueEmpty</span></span><a class="headerlink" href="#asyncio.QueueEmpty" title="Link to this definition">¶</a></dt><dd><p>This exception is raised when the <a class="reference internal" href="#asyncio.Queue.get_nowait" title="asyncio.Queue.get_nowait"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_nowait()</span></code></a> methodis called on an empty queue.</p></dd></dl>
<dl class="py exception"><dt class="sig sig-object py" id="asyncio.QueueFull"><em class="property"><span class="k"><span class="pre">exception</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">QueueFull</span></span><a class="headerlink" href="#asyncio.QueueFull" title="Link to this definition">¶</a></dt><dd><p>Exception raised when the <a class="reference internal" href="#asyncio.Queue.put_nowait" title="asyncio.Queue.put_nowait"><code class="xref py py-meth docutils literal notranslate"><span class="pre">put_nowait()</span></code></a> method is calledon a queue that has reached its <em>maxsize</em>.</p></dd></dl>
<dl class="py exception"><dt class="sig sig-object py" id="asyncio.QueueShutDown"><em class="property"><span class="k"><span class="pre">exception</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">QueueShutDown</span></span><a class="headerlink" href="#asyncio.QueueShutDown" title="Link to this definition">¶</a></dt><dd><p>Exception raised when <a class="reference internal" href="#asyncio.Queue.put" title="asyncio.Queue.put"><code class="xref py py-meth docutils literal notranslate"><span class="pre">put()</span></code></a> or <a class="reference internal" href="#asyncio.Queue.get" title="asyncio.Queue.get"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code></a> iscalled on a queue which has been shut down.</p><div class="versionadded"><p><span class="versionmodified added">Added in version 3.13.</span></p></div></dd></dl>
</section><section id="examples"><h2>Examples<a class="headerlink" href="#examples" title="Link to this heading">¶</a></h2><p id="asyncio-example-queue-dist">Queues can be used to distribute workload between severalconcurrent tasks:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span><span class="w"> </span><span class="nn">asyncio</span><span class="kn">import</span><span class="w"> </span><span class="nn">random</span><span class="kn">import</span><span class="w"> </span><span class="nn">time</span>
<span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">worker</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">queue</span><span class="p">):</span> <span class="k">while</span> <span class="kc">True</span><span class="p">:</span> <span class="c1"># Get a "work item" out of the queue.</span> <span class="n">sleep_for</span> <span class="o">=</span> <span class="k">await</span> <span class="n">queue</span><span class="o">.</span><span class="n">get</span><span class="p">()</span>
<span class="c1"># Sleep for the "sleep_for" seconds.</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="n">sleep_for</span><span class="p">)</span>
<span class="c1"># Notify the queue that the "work item" has been processed.</span> <span class="n">queue</span><span class="o">.</span><span class="n">task_done</span><span class="p">()</span>
<span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">'</span><span class="si">{</span><span class="n">name</span><span class="si">}</span><span class="s1"> has slept for </span><span class="si">{</span><span class="n">sleep_for</span><span class="si">:</span><span class="s1">.2f</span><span class="si">}</span><span class="s1"> seconds'</span><span class="p">)</span>
<span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">main</span><span class="p">():</span> <span class="c1"># Create a queue that we will use to store our "workload".</span> <span class="n">queue</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">Queue</span><span class="p">()</span>
<span class="c1"># Generate random timings and put them into the queue.</span> <span class="n">total_sleep_time</span> <span class="o">=</span> <span class="mi">0</span> <span class="k">for</span> <span class="n">_</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">20</span><span class="p">):</span> <span class="n">sleep_for</span> <span class="o">=</span> <span class="n">random</span><span class="o">.</span><span class="n">uniform</span><span class="p">(</span><span class="mf">0.05</span><span class="p">,</span> <span class="mf">1.0</span><span class="p">)</span> <span class="n">total_sleep_time</span> <span class="o">+=</span> <span class="n">sleep_for</span> <span class="n">queue</span><span class="o">.</span><span class="n">put_nowait</span><span class="p">(</span><span class="n">sleep_for</span><span class="p">)</span>
<span class="c1"># Create three worker tasks to process the queue concurrently.</span> <span class="n">tasks</span> <span class="o">=</span> <span class="p">[]</span> <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">3</span><span class="p">):</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">worker</span><span class="p">(</span><span class="sa">f</span><span class="s1">'worker-</span><span class="si">{</span><span class="n">i</span><span class="si">}</span><span class="s1">'</span><span class="p">,</span> <span class="n">queue</span><span class="p">))</span> <span class="n">tasks</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">task</span><span class="p">)</span>
<span class="c1"># Wait until the queue is fully processed.</span> <span class="n">started_at</span> <span class="o">=</span> <span class="n">time</span><span class="o">.</span><span class="n">monotonic</span><span class="p">()</span> <span class="k">await</span> <span class="n">queue</span><span class="o">.</span><span class="n">join</span><span class="p">()</span> <span class="n">total_slept_for</span> <span class="o">=</span> <span class="n">time</span><span class="o">.</span><span class="n">monotonic</span><span class="p">()</span> <span class="o">-</span> <span class="n">started_at</span>
<span class="c1"># Cancel our worker tasks.</span> <span class="k">for</span> <span class="n">task</span> <span class="ow">in</span> <span class="n">tasks</span><span class="p">:</span> <span class="n">task</span><span class="o">.</span><span class="n">cancel</span><span class="p">()</span> <span class="c1"># Wait until all worker tasks are cancelled.</span> <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">gather</span><span class="p">(</span><span class="o">*</span><span class="n">tasks</span><span class="p">,</span> <span class="n">return_exceptions</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">'===='</span><span class="p">)</span> <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">'3 workers slept in parallel for </span><span class="si">{</span><span class="n">total_slept_for</span><span class="si">:</span><span class="s1">.2f</span><span class="si">}</span><span class="s1"> seconds'</span><span class="p">)</span> <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">'total expected sleep time: </span><span class="si">{</span><span class="n">total_sleep_time</span><span class="si">:</span><span class="s1">.2f</span><span class="si">}</span><span class="s1"> seconds'</span><span class="p">)</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></pre></div></div></section></section>
<div class="clearer"></div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="Main"> <div class="sphinxsidebarwrapper"> <div> <h3><a href="../contents.html">Table of Contents</a></h3> <ul><li><a class="reference internal" href="#">Queues</a><ul><li><a class="reference internal" href="#queue">Queue</a></li><li><a class="reference internal" href="#priority-queue">Priority Queue</a></li><li><a class="reference internal" href="#lifo-queue">LIFO Queue</a></li><li><a class="reference internal" href="#exceptions">Exceptions</a></li><li><a class="reference internal" href="#examples">Examples</a></li></ul></li></ul>
</div> <div> <h4>Previous topic</h4> <p class="topless"><a href="asyncio-subprocess.html" title="previous chapter">Subprocesses</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="asyncio-exceptions.html" title="next chapter">Exceptions</a></p> </div> <script> document.addEventListener('DOMContentLoaded', () => { const title = document.querySelector('meta[property="og:title"]').content; const elements = document.querySelectorAll('.improvepage'); const pageurl = window.location.href.split('?')[0]; elements.forEach(element => { const url = new URL(element.href.split('?')[0].replace("-nojs", "")); url.searchParams.set('pagetitle', title); url.searchParams.set('pageurl', pageurl); url.searchParams.set('pagesource', "library/asyncio-queue.rst"); element.href = url.toString(); }); }); </script> <div role="note" aria-label="source link"> <h3>This page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a bug</a></li> <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li> <li> <a href="https://github.com/python/cpython/blob/main/Doc/library/asyncio-queue.rst?plain=1" rel="nofollow">Show source </a> </li> </ul> </div> </div><div id="sidebarbutton" title="Collapse sidebar"><span>«</span></div>
</div> <div class="clearer"></div> </div> <div class="related" role="navigation" aria-label="Related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="asyncio-exceptions.html" title="Exceptions" >next</a> |</li> <li class="right" > <a href="asyncio-subprocess.html" title="Subprocesses" >previous</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.15.0a6 Documentation</a> » </li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="ipc.html" >Networking and Interprocess Communication</a> »</li> <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> »</li> <li class="nav-item nav-item-this"><a href="">Queues</a></li> <li class="right">
<div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box"> <input type="submit" value="Go"> </form> </div> | </li> <li class="right"><label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> |</li> </ul> </div> <div class="footer"> © <a href="../copyright.html">Copyright</a> 2001 Python Software Foundation. <br> This page is licensed under the Python Software Foundation License Version 2. <br> Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. <br> See <a href="/license.html">History and License</a> for more information.<br> <br>
The Python Software Foundation is a non-profit corporation.<a href="https://www.python.org/psf/donations/">Please donate.</a><br> <br> Last updated on Mar 10, 2026 (08:58 UTC). <a href="/bugs.html">Found a bug</a>? <br>
Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3. </div>
</body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534<!DOCTYPE html>
<html lang="en" data-content_root="../"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta property="og:title" content="Runners" /><meta property="og:type" content="website" /><meta property="og:url" content="https://docs.python.org/3/library/asyncio-runner.html" /><meta property="og:site_name" content="Python documentation" /><meta property="og:description" content="Source code: Lib/asyncio/runners.py This section outlines high-level asyncio primitives to run asyncio code. They are built on top of an event loop with the aim to simplify async code usage for com..." /><meta property="og:image:width" content="1146" /><meta property="og:image:height" content="600" /><meta property="og:image" content="https://docs.python.org/3.15/_images/social_previews/summary_library_asyncio-runner_0cf58783.png" /><meta property="og:image:alt" content="Source code: Lib/asyncio/runners.py This section outlines high-level asyncio primitives to run asyncio code. They are built on top of an event loop with the aim to simplify async code usage for com..." /><meta name="description" content="Source code: Lib/asyncio/runners.py This section outlines high-level asyncio primitives to run asyncio code. They are built on top of an event loop with the aim to simplify async code usage for com..." /><meta name="twitter:card" content="summary_large_image" /><meta name="theme-color" content="#3776ab">
<title>Runners — Python 3.15.0a6 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" /> <link rel="stylesheet" type="text/css" href="../_static/classic.css?v=234b1a7c" /> <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=89a2f22a" /> <link rel="stylesheet" type="text/css" href="../_static/profiling-sampling-visualization.css?v=0c2600ae" /> <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" /> <script src="../_static/documentation_options.js?v=6b7c9ff5"></script> <script src="../_static/doctools.js?v=9bcbadda"></script> <script src="../_static/sphinx_highlight.js?v=dc90522c"></script> <script src="../_static/profiling-sampling-visualization.js?v=9811ed04"></script> <script src="../_static/sidebar.js"></script> <link rel="search" type="application/opensearchdescription+xml" title="Search within Python 3.15.0a6 documentation" href="../_static/opensearch.xml"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="copyright" title="Copyright" href="../copyright.html" /> <link rel="next" title="Coroutines and Tasks" href="asyncio-task.html" /> <link rel="prev" title="asyncio — Asynchronous I/O" href="asyncio.html" /> <script defer file-types="bz2,epub,zip" data-domain="docs.python.org" src="https://analytics.python.org/js/script.file-downloads.outbound-links.js"></script> <link rel="canonical" href="https://docs.python.org/3/library/asyncio-runner.html">
<style> @media only screen { table.full-width-table { width: 100%; } } </style><link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css"> <link rel="shortcut icon" type="image/png" href="../_static/py.svg"> <script type="text/javascript" src="../_static/copybutton.js"></script> <script type="text/javascript" src="../_static/menu.js"></script> <script type="text/javascript" src="../_static/search-focus.js"></script> <script type="text/javascript" src="../_static/themetoggle.js"></script> <script type="text/javascript" src="../_static/rtd_switcher.js"></script> <meta name="readthedocs-addons-api-version" content="1">
</head><body><div class="mobile-nav"> <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation" aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu"> <nav class="nav-content" role="navigation"> <label for="menuToggler" class="toggler__label"> <span></span> </label> <span class="nav-items-wrapper"> <a href="https://www.python.org/" class="nav-logo"> <img src="../_static/py.svg" alt="Python logo"> </a> <span class="version_switcher_placeholder"></span> <form role="search" class="search" action="../search.html" method="get"> <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon"> <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> </svg> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q"> <input type="submit" value="Go"> </form> </span> </nav> <div class="menu-wrapper"> <nav class="menu" role="navigation" aria-label="main navigation"> <div class="language_switcher_placeholder"></div> <label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> <div> <h3><a href="../contents.html">Table of Contents</a></h3> <ul><li><a class="reference internal" href="#">Runners</a><ul><li><a class="reference internal" href="#running-an-asyncio-program">Running an asyncio Program</a></li><li><a class="reference internal" href="#runner-context-manager">Runner context manager</a></li><li><a class="reference internal" href="#handling-keyboard-interruption">Handling Keyboard Interruption</a></li></ul></li></ul>
</div> <div> <h4>Previous topic</h4> <p class="topless"><a href="asyncio.html" title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">asyncio</span></code> — Asynchronous I/O</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="asyncio-task.html" title="next chapter">Coroutines and Tasks</a></p> </div> <script> document.addEventListener('DOMContentLoaded', () => { const title = document.querySelector('meta[property="og:title"]').content; const elements = document.querySelectorAll('.improvepage'); const pageurl = window.location.href.split('?')[0]; elements.forEach(element => { const url = new URL(element.href.split('?')[0].replace("-nojs", "")); url.searchParams.set('pagetitle', title); url.searchParams.set('pageurl', pageurl); url.searchParams.set('pagesource', "library/asyncio-runner.rst"); element.href = url.toString(); }); }); </script> <div role="note" aria-label="source link"> <h3>This page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a bug</a></li> <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li> <li> <a href="https://github.com/python/cpython/blob/main/Doc/library/asyncio-runner.rst?plain=1" rel="nofollow">Show source </a> </li> </ul> </div> </nav> </div></div>
<div class="related" role="navigation" aria-label="Related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="asyncio-task.html" title="Coroutines and Tasks" accesskey="N">next</a> |</li> <li class="right" > <a href="asyncio.html" title="asyncio — Asynchronous I/O" accesskey="P">previous</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.15.0a6 Documentation</a> » </li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="ipc.html" >Networking and Interprocess Communication</a> »</li> <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> »</li> <li class="nav-item nav-item-this"><a href="">Runners</a></li> <li class="right">
<div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box"> <input type="submit" value="Go"> </form> </div> | </li> <li class="right"><label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> |</li> </ul> </div>
<div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <section id="runners"><h1>Runners<a class="headerlink" href="#runners" title="Link to this heading">¶</a></h1><p><strong>Source code:</strong> <a class="extlink-source reference external" href="https://github.com/python/cpython/tree/main/Lib/asyncio/runners.py">Lib/asyncio/runners.py</a></p><p>This section outlines high-level asyncio primitives to run asyncio code.</p><p>They are built on top of an <a class="reference internal" href="asyncio-eventloop.html#asyncio-event-loop"><span class="std std-ref">event loop</span></a> with the aimto simplify async code usage for common wide-spread scenarios.</p><nav class="contents local" id="contents"><ul class="simple"><li><p><a class="reference internal" href="#running-an-asyncio-program" id="id1">Running an asyncio Program</a></p></li><li><p><a class="reference internal" href="#runner-context-manager" id="id2">Runner context manager</a></p></li><li><p><a class="reference internal" href="#handling-keyboard-interruption" id="id3">Handling Keyboard Interruption</a></p></li></ul></nav><section id="running-an-asyncio-program"><h2><a class="toc-backref" href="#id1" role="doc-backlink">Running an asyncio Program</a><a class="headerlink" href="#running-an-asyncio-program" title="Link to this heading">¶</a></h2><dl class="py function"><dt class="sig sig-object py" id="asyncio.run"><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">run</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="keyword-only-separator o"><abbr title="Keyword-only parameters separator (PEP 3102)"><span class="pre">*</span></abbr></span></em>, <em class="sig-param"><span class="n"><span class="pre">debug</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">loop_factory</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.run" title="Link to this definition">¶</a></dt><dd><p>Execute <em>coro</em> in an asyncio event loop and return the result.</p><p>The argument can be any awaitable object.</p><p>This function runs the awaitable, taking care of managing theasyncio event loop, <em>finalizing asynchronous generators</em>, andclosing the executor.</p><p>This function cannot be called when another asyncio event loop isrunning in the same thread.</p><p>If <em>debug</em> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, the event loop will be run in debug mode. <code class="docutils literal notranslate"><span class="pre">False</span></code> disablesdebug mode explicitly. <code class="docutils literal notranslate"><span class="pre">None</span></code> is used to respect the global<a class="reference internal" href="asyncio-dev.html#asyncio-debug-mode"><span class="std std-ref">Debug Mode</span></a> settings.</p><p>If <em>loop_factory</em> is not <code class="docutils literal notranslate"><span class="pre">None</span></code>, it is used to create a new event loop;otherwise <a class="reference internal" href="asyncio-eventloop.html#asyncio.new_event_loop" title="asyncio.new_event_loop"><code class="xref py py-func docutils literal notranslate"><span class="pre">asyncio.new_event_loop()</span></code></a> is used. The loop is closed at the end.This function should be used as a main entry point for asyncio programs,and should ideally only be called once. It is recommended to use<em>loop_factory</em> to configure the event loop instead of policies.Passing <a class="reference internal" href="asyncio-eventloop.html#asyncio.EventLoop" title="asyncio.EventLoop"><code class="xref py py-class docutils literal notranslate"><span class="pre">asyncio.EventLoop</span></code></a> allows running asyncio without thepolicy system.</p><p>The executor is given a timeout duration of 5 minutes to shutdown.If the executor hasn’t finished within that duration, a warning isemitted and the executor is closed.</p><p>Example:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">main</span><span class="p">():</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> <span class="nb">print</span><span class="p">(</span><span class="s1">'hello'</span><span class="p">)</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></pre></div></div><div class="versionadded"><p><span class="versionmodified added">Added in version 3.7.</span></p></div><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.9: </span>Updated to use <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.shutdown_default_executor" title="asyncio.loop.shutdown_default_executor"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.shutdown_default_executor()</span></code></a>.</p></div><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.10: </span><em>debug</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code> by default to respect the global debug mode settings.</p></div><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.12: </span>Added <em>loop_factory</em> parameter.</p></div><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.14: </span><em>coro</em> can be any awaitable object.</p></div><div class="admonition note"><p class="admonition-title">Note</p><p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">asyncio</span></code> policy system is deprecated and will be removedin Python 3.16; from there on, an explicit <em>loop_factory</em> is neededto configure the event loop.</p></div></dd></dl>
</section><section id="runner-context-manager"><h2><a class="toc-backref" href="#id2" role="doc-backlink">Runner context manager</a><a class="headerlink" href="#runner-context-manager" title="Link to this heading">¶</a></h2><dl class="py class"><dt class="sig sig-object py" id="asyncio.Runner"><em class="property"><span class="k"><span class="pre">class</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">Runner</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="keyword-only-separator o"><abbr title="Keyword-only parameters separator (PEP 3102)"><span class="pre">*</span></abbr></span></em>, <em class="sig-param"><span class="n"><span class="pre">debug</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">loop_factory</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.Runner" title="Link to this definition">¶</a></dt><dd><p>A context manager that simplifies <em>multiple</em> async function calls in the samecontext.</p><p>Sometimes several top-level async functions should be called in the same <a class="reference internal" href="asyncio-eventloop.html#asyncio-event-loop"><span class="std std-ref">eventloop</span></a> and <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>.</p><p>If <em>debug</em> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, the event loop will be run in debug mode. <code class="docutils literal notranslate"><span class="pre">False</span></code> disablesdebug mode explicitly. <code class="docutils literal notranslate"><span class="pre">None</span></code> is used to respect the global<a class="reference internal" href="asyncio-dev.html#asyncio-debug-mode"><span class="std std-ref">Debug Mode</span></a> settings.</p><p><em>loop_factory</em> could be used for overriding the loop creation.It is the responsibility of the <em>loop_factory</em> to set the created loop as thecurrent one. By default <a class="reference internal" href="asyncio-eventloop.html#asyncio.new_event_loop" title="asyncio.new_event_loop"><code class="xref py py-func docutils literal notranslate"><span class="pre">asyncio.new_event_loop()</span></code></a> is used and set ascurrent event loop with <a class="reference internal" href="asyncio-eventloop.html#asyncio.set_event_loop" title="asyncio.set_event_loop"><code class="xref py py-func docutils literal notranslate"><span class="pre">asyncio.set_event_loop()</span></code></a> if <em>loop_factory</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p><p>Basically, <a class="reference internal" href="#asyncio.run" title="asyncio.run"><code class="xref py py-func docutils literal notranslate"><span class="pre">asyncio.run()</span></code></a> example can be rewritten with the runner usage:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">main</span><span class="p">():</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> <span class="nb">print</span><span class="p">(</span><span class="s1">'hello'</span><span class="p">)</span>
<span class="k">with</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">Runner</span><span class="p">()</span> <span class="k">as</span> <span class="n">runner</span><span class="p">:</span> <span class="n">runner</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="n">main</span><span class="p">())</span></pre></div></div><div class="versionadded"><p><span class="versionmodified added">Added in version 3.11.</span></p></div><dl class="py method"><dt class="sig sig-object py" id="asyncio.Runner.run"><span class="sig-name descname"><span class="pre">run</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="keyword-only-separator o"><abbr title="Keyword-only parameters separator (PEP 3102)"><span class="pre">*</span></abbr></span></em>, <em class="sig-param"><span class="n"><span class="pre">context</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Runner.run" title="Link to this definition">¶</a></dt><dd><p>Execute <em>coro</em> in the embedded event loop.</p><p>The argument can be any awaitable object.</p><p>If the argument is a coroutine, it is wrapped in a Task.</p><p>An optional keyword-only <em>context</em> argument allows specifying acustom <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 code to run in.The runner’s default context is used if context is <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p><p>Returns the awaitable’s result or raises an exception.</p><p>This function cannot be called when another asyncio event loop isrunning in the same thread.</p><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.14: </span><em>coro</em> can be any awaitable object.</p></div></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.Runner.close"><span class="sig-name descname"><span class="pre">close</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Runner.close" title="Link to this definition">¶</a></dt><dd><p>Close the runner.</p><p>Finalize asynchronous generators, shutdown default executor, close the event loopand release embedded <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>.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.Runner.get_loop"><span class="sig-name descname"><span class="pre">get_loop</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Runner.get_loop" title="Link to this definition">¶</a></dt><dd><p>Return the event loop associated with the runner instance.</p></dd></dl>
<div class="admonition note"><p class="admonition-title">Note</p><p><code class="xref py py-class docutils literal notranslate"><span class="pre">Runner</span></code> uses the lazy initialization strategy, its constructor doesn’tinitialize underlying low-level structures.</p><p>Embedded <em>loop</em> and <em>context</em> are created at the <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> body enteringor the first call of <a class="reference internal" href="#asyncio.run" title="asyncio.run"><code class="xref py py-meth docutils literal notranslate"><span class="pre">run()</span></code></a> or <a class="reference internal" href="#asyncio.Runner.get_loop" title="asyncio.Runner.get_loop"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_loop()</span></code></a>.</p></div></dd></dl>
</section><section id="handling-keyboard-interruption"><h2><a class="toc-backref" href="#id3" role="doc-backlink">Handling Keyboard Interruption</a><a class="headerlink" href="#handling-keyboard-interruption" title="Link to this heading">¶</a></h2><div class="versionadded"><p><span class="versionmodified added">Added in version 3.11.</span></p></div><p>When <a class="reference internal" href="signal.html#signal.SIGINT" title="signal.SIGINT"><code class="xref py py-const docutils literal notranslate"><span class="pre">signal.SIGINT</span></code></a> is raised by <kbd class="kbd docutils literal notranslate">Ctrl</kbd>-<kbd class="kbd docutils literal notranslate">C</kbd>, <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>exception is raised in the main thread by default. However this doesn’t work with<a class="reference internal" href="asyncio.html#module-asyncio" title="asyncio: Asynchronous I/O."><code class="xref py py-mod docutils literal notranslate"><span class="pre">asyncio</span></code></a> because it can interrupt asyncio internals and can hang the program fromexiting.</p><p>To mitigate this issue, <a class="reference internal" href="asyncio.html#module-asyncio" title="asyncio: Asynchronous I/O."><code class="xref py py-mod docutils literal notranslate"><span class="pre">asyncio</span></code></a> handles <a class="reference internal" href="signal.html#signal.SIGINT" title="signal.SIGINT"><code class="xref py py-const docutils literal notranslate"><span class="pre">signal.SIGINT</span></code></a> as follows:</p><ol class="arabic simple"><li><p><a class="reference internal" href="#asyncio.Runner.run" title="asyncio.Runner.run"><code class="xref py py-meth docutils literal notranslate"><span class="pre">asyncio.Runner.run()</span></code></a> installs a custom <a class="reference internal" href="signal.html#signal.SIGINT" title="signal.SIGINT"><code class="xref py py-const docutils literal notranslate"><span class="pre">signal.SIGINT</span></code></a> handler beforeany user code is executed and removes it when exiting from the function.</p></li><li><p>The <a class="reference internal" href="#asyncio.Runner" title="asyncio.Runner"><code class="xref py py-class docutils literal notranslate"><span class="pre">Runner</span></code></a> creates the main task for the passed coroutine for itsexecution.</p></li><li><p>When <a class="reference internal" href="signal.html#signal.SIGINT" title="signal.SIGINT"><code class="xref py py-const docutils literal notranslate"><span class="pre">signal.SIGINT</span></code></a> is raised by <kbd class="kbd docutils literal notranslate">Ctrl</kbd>-<kbd class="kbd docutils literal notranslate">C</kbd>, the custom signal handlercancels the main task by calling <a class="reference internal" href="asyncio-task.html#asyncio.Task.cancel" title="asyncio.Task.cancel"><code class="xref py py-meth docutils literal notranslate"><span class="pre">asyncio.Task.cancel()</span></code></a> which raises<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> inside the main task. This causes the Python stackto unwind, <code class="docutils literal notranslate"><span class="pre">try/except</span></code> and <code class="docutils literal notranslate"><span class="pre">try/finally</span></code> blocks can be used for resourcecleanup. After the main task is cancelled, <a class="reference internal" href="#asyncio.Runner.run" title="asyncio.Runner.run"><code class="xref py py-meth docutils literal notranslate"><span class="pre">asyncio.Runner.run()</span></code></a> raises<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>.</p></li><li><p>A user could write a tight loop which cannot be interrupted by<a class="reference internal" href="asyncio-task.html#asyncio.Task.cancel" title="asyncio.Task.cancel"><code class="xref py py-meth docutils literal notranslate"><span class="pre">asyncio.Task.cancel()</span></code></a>, in which case the second following <kbd class="kbd docutils literal notranslate">Ctrl</kbd>-<kbd class="kbd docutils literal notranslate">C</kbd>immediately raises the <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> without cancelling the main task.</p></li></ol></section></section>
<div class="clearer"></div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="Main"> <div class="sphinxsidebarwrapper"> <div> <h3><a href="../contents.html">Table of Contents</a></h3> <ul><li><a class="reference internal" href="#">Runners</a><ul><li><a class="reference internal" href="#running-an-asyncio-program">Running an asyncio Program</a></li><li><a class="reference internal" href="#runner-context-manager">Runner context manager</a></li><li><a class="reference internal" href="#handling-keyboard-interruption">Handling Keyboard Interruption</a></li></ul></li></ul>
</div> <div> <h4>Previous topic</h4> <p class="topless"><a href="asyncio.html" title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">asyncio</span></code> — Asynchronous I/O</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="asyncio-task.html" title="next chapter">Coroutines and Tasks</a></p> </div> <script> document.addEventListener('DOMContentLoaded', () => { const title = document.querySelector('meta[property="og:title"]').content; const elements = document.querySelectorAll('.improvepage'); const pageurl = window.location.href.split('?')[0]; elements.forEach(element => { const url = new URL(element.href.split('?')[0].replace("-nojs", "")); url.searchParams.set('pagetitle', title); url.searchParams.set('pageurl', pageurl); url.searchParams.set('pagesource', "library/asyncio-runner.rst"); element.href = url.toString(); }); }); </script> <div role="note" aria-label="source link"> <h3>This page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a bug</a></li> <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li> <li> <a href="https://github.com/python/cpython/blob/main/Doc/library/asyncio-runner.rst?plain=1" rel="nofollow">Show source </a> </li> </ul> </div> </div><div id="sidebarbutton" title="Collapse sidebar"><span>«</span></div>
</div> <div class="clearer"></div> </div> <div class="related" role="navigation" aria-label="Related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="asyncio-task.html" title="Coroutines and Tasks" >next</a> |</li> <li class="right" > <a href="asyncio.html" title="asyncio — Asynchronous I/O" >previous</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.15.0a6 Documentation</a> » </li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="ipc.html" >Networking and Interprocess Communication</a> »</li> <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> »</li> <li class="nav-item nav-item-this"><a href="">Runners</a></li> <li class="right">
<div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box"> <input type="submit" value="Go"> </form> </div> | </li> <li class="right"><label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> |</li> </ul> </div> <div class="footer"> © <a href="../copyright.html">Copyright</a> 2001 Python Software Foundation. <br> This page is licensed under the Python Software Foundation License Version 2. <br> Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. <br> See <a href="/license.html">History and License</a> for more information.<br> <br>
The Python Software Foundation is a non-profit corporation.<a href="https://www.python.org/psf/donations/">Please donate.</a><br> <br> Last updated on Mar 10, 2026 (08:58 UTC). <a href="/bugs.html">Found a bug</a>? <br>
Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3. </div>
</body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941<!DOCTYPE html>
<html lang="en" data-content_root="../"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta property="og:title" content="Streams" /><meta property="og:type" content="website" /><meta property="og:url" content="https://docs.python.org/3/library/asyncio-stream.html" /><meta property="og:site_name" content="Python documentation" /><meta property="og:description" content="Source code: Lib/asyncio/streams.py Streams are high-level async/await-ready primitives to work with network connections. Streams allow sending and receiving data without using callbacks or low-lev..." /><meta property="og:image:width" content="1146" /><meta property="og:image:height" content="600" /><meta property="og:image" content="https://docs.python.org/3.15/_images/social_previews/summary_library_asyncio-stream_129da5fd.png" /><meta property="og:image:alt" content="Source code: Lib/asyncio/streams.py Streams are high-level async/await-ready primitives to work with network connections. Streams allow sending and receiving data without using callbacks or low-lev..." /><meta name="description" content="Source code: Lib/asyncio/streams.py Streams are high-level async/await-ready primitives to work with network connections. Streams allow sending and receiving data without using callbacks or low-lev..." /><meta name="twitter:card" content="summary_large_image" /><meta name="theme-color" content="#3776ab">
<title>Streams — Python 3.15.0a6 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" /> <link rel="stylesheet" type="text/css" href="../_static/classic.css?v=234b1a7c" /> <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=89a2f22a" /> <link rel="stylesheet" type="text/css" href="../_static/profiling-sampling-visualization.css?v=0c2600ae" /> <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" /> <script src="../_static/documentation_options.js?v=6b7c9ff5"></script> <script src="../_static/doctools.js?v=9bcbadda"></script> <script src="../_static/sphinx_highlight.js?v=dc90522c"></script> <script src="../_static/profiling-sampling-visualization.js?v=9811ed04"></script> <script src="../_static/sidebar.js"></script> <link rel="search" type="application/opensearchdescription+xml" title="Search within Python 3.15.0a6 documentation" href="../_static/opensearch.xml"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="copyright" title="Copyright" href="../copyright.html" /> <link rel="next" title="Synchronization Primitives" href="asyncio-sync.html" /> <link rel="prev" title="Coroutines and Tasks" href="asyncio-task.html" /> <script defer file-types="bz2,epub,zip" data-domain="docs.python.org" src="https://analytics.python.org/js/script.file-downloads.outbound-links.js"></script> <link rel="canonical" href="https://docs.python.org/3/library/asyncio-stream.html">
<style> @media only screen { table.full-width-table { width: 100%; } } </style><link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css"> <link rel="shortcut icon" type="image/png" href="../_static/py.svg"> <script type="text/javascript" src="../_static/copybutton.js"></script> <script type="text/javascript" src="../_static/menu.js"></script> <script type="text/javascript" src="../_static/search-focus.js"></script> <script type="text/javascript" src="../_static/themetoggle.js"></script> <script type="text/javascript" src="../_static/rtd_switcher.js"></script> <meta name="readthedocs-addons-api-version" content="1">
</head><body><div class="mobile-nav"> <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation" aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu"> <nav class="nav-content" role="navigation"> <label for="menuToggler" class="toggler__label"> <span></span> </label> <span class="nav-items-wrapper"> <a href="https://www.python.org/" class="nav-logo"> <img src="../_static/py.svg" alt="Python logo"> </a> <span class="version_switcher_placeholder"></span> <form role="search" class="search" action="../search.html" method="get"> <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon"> <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> </svg> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q"> <input type="submit" value="Go"> </form> </span> </nav> <div class="menu-wrapper"> <nav class="menu" role="navigation" aria-label="main navigation"> <div class="language_switcher_placeholder"></div> <label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> <div> <h3><a href="../contents.html">Table of Contents</a></h3> <ul><li><a class="reference internal" href="#">Streams</a><ul><li><a class="reference internal" href="#streamreader">StreamReader</a></li><li><a class="reference internal" href="#streamwriter">StreamWriter</a></li><li><a class="reference internal" href="#examples">Examples</a><ul><li><a class="reference internal" href="#tcp-echo-client-using-streams">TCP echo client using streams</a></li><li><a class="reference internal" href="#tcp-echo-server-using-streams">TCP echo server using streams</a></li><li><a class="reference internal" href="#get-http-headers">Get HTTP headers</a></li><li><a class="reference internal" href="#register-an-open-socket-to-wait-for-data-using-streams">Register an open socket to wait for data using streams</a></li></ul></li></ul></li></ul>
</div> <div> <h4>Previous topic</h4> <p class="topless"><a href="asyncio-task.html" title="previous chapter">Coroutines and Tasks</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="asyncio-sync.html" title="next chapter">Synchronization Primitives</a></p> </div> <script> document.addEventListener('DOMContentLoaded', () => { const title = document.querySelector('meta[property="og:title"]').content; const elements = document.querySelectorAll('.improvepage'); const pageurl = window.location.href.split('?')[0]; elements.forEach(element => { const url = new URL(element.href.split('?')[0].replace("-nojs", "")); url.searchParams.set('pagetitle', title); url.searchParams.set('pageurl', pageurl); url.searchParams.set('pagesource', "library/asyncio-stream.rst"); element.href = url.toString(); }); }); </script> <div role="note" aria-label="source link"> <h3>This page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a bug</a></li> <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li> <li> <a href="https://github.com/python/cpython/blob/main/Doc/library/asyncio-stream.rst?plain=1" rel="nofollow">Show source </a> </li> </ul> </div> </nav> </div></div>
<div class="related" role="navigation" aria-label="Related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="asyncio-sync.html" title="Synchronization Primitives" accesskey="N">next</a> |</li> <li class="right" > <a href="asyncio-task.html" title="Coroutines and Tasks" accesskey="P">previous</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.15.0a6 Documentation</a> » </li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="ipc.html" >Networking and Interprocess Communication</a> »</li> <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> »</li> <li class="nav-item nav-item-this"><a href="">Streams</a></li> <li class="right">
<div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box"> <input type="submit" value="Go"> </form> </div> | </li> <li class="right"><label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> |</li> </ul> </div>
<div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <section id="streams"><span id="asyncio-streams"></span><h1>Streams<a class="headerlink" href="#streams" title="Link to this heading">¶</a></h1><p><strong>Source code:</strong> <a class="extlink-source reference external" href="https://github.com/python/cpython/tree/main/Lib/asyncio/streams.py">Lib/asyncio/streams.py</a></p><hr class="docutils" /><p>Streams are high-level async/await-ready primitives to work withnetwork connections. Streams allow sending and receiving data withoutusing callbacks or low-level protocols and transports.</p><p id="asyncio-example-stream">Here is an example of a TCP echo client written using asynciostreams:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span><span class="w"> </span><span class="nn">asyncio</span>
<span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">tcp_echo_client</span><span class="p">(</span><span class="n">message</span><span class="p">):</span> <span class="n">reader</span><span class="p">,</span> <span class="n">writer</span> <span class="o">=</span> <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">open_connection</span><span class="p">(</span> <span class="s1">'127.0.0.1'</span><span class="p">,</span> <span class="mi">8888</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">'Send: </span><span class="si">{</span><span class="n">message</span><span class="si">!r}</span><span class="s1">'</span><span class="p">)</span> <span class="n">writer</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">message</span><span class="o">.</span><span class="n">encode</span><span class="p">())</span> <span class="k">await</span> <span class="n">writer</span><span class="o">.</span><span class="n">drain</span><span class="p">()</span>
<span class="n">data</span> <span class="o">=</span> <span class="k">await</span> <span class="n">reader</span><span class="o">.</span><span class="n">read</span><span class="p">(</span><span class="mi">100</span><span class="p">)</span> <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">'Received: </span><span class="si">{</span><span class="n">data</span><span class="o">.</span><span class="n">decode</span><span class="p">()</span><span class="si">!r}</span><span class="s1">'</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">'Close the connection'</span><span class="p">)</span> <span class="n">writer</span><span class="o">.</span><span class="n">close</span><span class="p">()</span> <span class="k">await</span> <span class="n">writer</span><span class="o">.</span><span class="n">wait_closed</span><span class="p">()</span>
<span class="n">asyncio</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="n">tcp_echo_client</span><span class="p">(</span><span class="s1">'Hello World!'</span><span class="p">))</span></pre></div></div><p>See also the <a class="reference internal" href="#examples">Examples</a> section below.</p><p class="rubric">Stream Functions</p><p>The following top-level asyncio functions can be used to createand work with streams:</p><dl class="py function"><dt class="sig sig-object py" id="asyncio.open_connection"><em class="property"><span class="k"><span class="pre">async</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">open_connection</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">host</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">port</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="keyword-only-separator o"><abbr title="Keyword-only parameters separator (PEP 3102)"><span class="pre">*</span></abbr></span></em>, <em class="sig-param"><span class="n"><span class="pre">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">ssl</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">family</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">0</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">proto</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">0</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">flags</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">0</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">sock</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">local_addr</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">server_hostname</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">ssl_handshake_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">ssl_shutdown_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">happy_eyeballs_delay</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">interleave</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.open_connection" title="Link to this definition">¶</a></dt><dd><p>Establish a network connection and return a pair of<code class="docutils literal notranslate"><span class="pre">(reader,</span> <span class="pre">writer)</span></code> objects.</p><p>The returned <em>reader</em> and <em>writer</em> objects are instances of<a class="reference internal" href="#asyncio.StreamReader" title="asyncio.StreamReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamReader</span></code></a> and <a class="reference internal" href="#asyncio.StreamWriter" title="asyncio.StreamWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamWriter</span></code></a> classes.</p><p><em>limit</em> determines the buffer size limit used by thereturned <a class="reference internal" href="#asyncio.StreamReader" title="asyncio.StreamReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamReader</span></code></a> instance. By default the <em>limit</em>is set to 64 KiB.</p><p>The rest of the arguments are passed directly to<a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.create_connection" title="asyncio.loop.create_connection"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.create_connection()</span></code></a>.</p><div class="admonition note"><p class="admonition-title">Note</p><p>The <em>sock</em> argument transfers ownership of the socket to the<a class="reference internal" href="#asyncio.StreamWriter" title="asyncio.StreamWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamWriter</span></code></a> created. To close the socket, call its<a class="reference internal" href="#asyncio.StreamWriter.close" title="asyncio.StreamWriter.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a> method.</p></div><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.7: </span>Added the <em>ssl_handshake_timeout</em> parameter.</p></div><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.8: </span>Added the <em>happy_eyeballs_delay</em> and <em>interleave</em> parameters.</p></div><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.10: </span>Removed the <em>loop</em> parameter.</p></div><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.11: </span>Added the <em>ssl_shutdown_timeout</em> parameter.</p></div></dd></dl>
<dl class="py function"><dt class="sig sig-object py" id="asyncio.start_server"><em class="property"><span class="k"><span class="pre">async</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">start_server</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">client_connected_cb</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">host</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">port</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="keyword-only-separator o"><abbr title="Keyword-only parameters separator (PEP 3102)"><span class="pre">*</span></abbr></span></em>, <em class="sig-param"><span class="n"><span class="pre">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">family</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">socket.AF_UNSPEC</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">flags</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">socket.AI_PASSIVE</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">sock</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">backlog</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">100</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">ssl</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">reuse_address</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">reuse_port</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">keep_alive</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">ssl_handshake_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">ssl_shutdown_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">start_serving</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">True</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.start_server" title="Link to this definition">¶</a></dt><dd><p>Start a socket server.</p><p>The <em>client_connected_cb</em> callback is called whenever a new clientconnection is established. It receives a <code class="docutils literal notranslate"><span class="pre">(reader,</span> <span class="pre">writer)</span></code> pairas two arguments, instances of the <a class="reference internal" href="#asyncio.StreamReader" title="asyncio.StreamReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamReader</span></code></a> and<a class="reference internal" href="#asyncio.StreamWriter" title="asyncio.StreamWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamWriter</span></code></a> classes.</p><p><em>client_connected_cb</em> can be a plain callable or a<a class="reference internal" href="asyncio-task.html#coroutine"><span class="std std-ref">coroutine function</span></a>; if it is a coroutine function,it will be automatically scheduled as a <a class="reference internal" href="asyncio-task.html#asyncio.Task" title="asyncio.Task"><code class="xref py py-class docutils literal notranslate"><span class="pre">Task</span></code></a>.</p><p><em>limit</em> determines the buffer size limit used by thereturned <a class="reference internal" href="#asyncio.StreamReader" title="asyncio.StreamReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamReader</span></code></a> instance. By default the <em>limit</em>is set to 64 KiB.</p><p>The rest of the arguments are passed directly to<a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.create_server" title="asyncio.loop.create_server"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.create_server()</span></code></a>.</p><div class="admonition note"><p class="admonition-title">Note</p><p>The <em>sock</em> argument transfers ownership of the socket to theserver created. To close the socket, call the server’s<a class="reference internal" href="asyncio-eventloop.html#asyncio.Server.close" title="asyncio.Server.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a> method.</p></div><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.7: </span>Added the <em>ssl_handshake_timeout</em> and <em>start_serving</em> parameters.</p></div><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.10: </span>Removed the <em>loop</em> parameter.</p></div><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.11: </span>Added the <em>ssl_shutdown_timeout</em> parameter.</p></div><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.13: </span>Added the <em>keep_alive</em> parameter.</p></div></dd></dl>
<p class="rubric">Unix Sockets</p><dl class="py function"><dt class="sig sig-object py" id="asyncio.open_unix_connection"><em class="property"><span class="k"><span class="pre">async</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">open_unix_connection</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">path</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="keyword-only-separator o"><abbr title="Keyword-only parameters separator (PEP 3102)"><span class="pre">*</span></abbr></span></em>, <em class="sig-param"><span class="n"><span class="pre">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">ssl</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">sock</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">server_hostname</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">ssl_handshake_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">ssl_shutdown_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.open_unix_connection" title="Link to this definition">¶</a></dt><dd><p>Establish a Unix socket connection and return a pair of<code class="docutils literal notranslate"><span class="pre">(reader,</span> <span class="pre">writer)</span></code>.</p><p>Similar to <a class="reference internal" href="#asyncio.open_connection" title="asyncio.open_connection"><code class="xref py py-func docutils literal notranslate"><span class="pre">open_connection()</span></code></a> but operates on Unix sockets.</p><p>See also the documentation of <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.create_unix_connection" title="asyncio.loop.create_unix_connection"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.create_unix_connection()</span></code></a>.</p><div class="admonition note"><p class="admonition-title">Note</p><p>The <em>sock</em> argument transfers ownership of the socket to the<a class="reference internal" href="#asyncio.StreamWriter" title="asyncio.StreamWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamWriter</span></code></a> created. To close the socket, call its<a class="reference internal" href="#asyncio.StreamWriter.close" title="asyncio.StreamWriter.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a> method.</p></div><div class="availability docutils container"><p><a class="reference internal" href="intro.html#availability"><span class="std std-ref">Availability</span></a>: Unix.</p></div><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.7: </span>Added the <em>ssl_handshake_timeout</em> parameter.The <em>path</em> parameter can now be a <a class="reference internal" href="../glossary.html#term-path-like-object"><span class="xref std std-term">path-like object</span></a></p></div><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.10: </span>Removed the <em>loop</em> parameter.</p></div><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.11: </span>Added the <em>ssl_shutdown_timeout</em> parameter.</p></div></dd></dl>
<dl class="py function"><dt class="sig sig-object py" id="asyncio.start_unix_server"><em class="property"><span class="k"><span class="pre">async</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">start_unix_server</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">client_connected_cb</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">path</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="keyword-only-separator o"><abbr title="Keyword-only parameters separator (PEP 3102)"><span class="pre">*</span></abbr></span></em>, <em class="sig-param"><span class="n"><span class="pre">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">sock</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">backlog</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">100</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">ssl</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">ssl_handshake_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">ssl_shutdown_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">start_serving</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">True</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">cleanup_socket</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">True</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.start_unix_server" title="Link to this definition">¶</a></dt><dd><p>Start a Unix socket server.</p><p>Similar to <a class="reference internal" href="#asyncio.start_server" title="asyncio.start_server"><code class="xref py py-func docutils literal notranslate"><span class="pre">start_server()</span></code></a> but works with Unix sockets.</p><p>If <em>cleanup_socket</em> is true then the Unix socket will automaticallybe removed from the filesystem when the server is closed, unless thesocket has been replaced after the server has been created.</p><p>See also the documentation of <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.create_unix_server" title="asyncio.loop.create_unix_server"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.create_unix_server()</span></code></a>.</p><div class="admonition note"><p class="admonition-title">Note</p><p>The <em>sock</em> argument transfers ownership of the socket to theserver created. To close the socket, call the server’s<a class="reference internal" href="asyncio-eventloop.html#asyncio.Server.close" title="asyncio.Server.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a> method.</p></div><div class="availability docutils container"><p><a class="reference internal" href="intro.html#availability"><span class="std std-ref">Availability</span></a>: Unix.</p></div><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.7: </span>Added the <em>ssl_handshake_timeout</em> and <em>start_serving</em> parameters.The <em>path</em> parameter can now be a <a class="reference internal" href="../glossary.html#term-path-like-object"><span class="xref std std-term">path-like object</span></a>.</p></div><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.10: </span>Removed the <em>loop</em> parameter.</p></div><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.11: </span>Added the <em>ssl_shutdown_timeout</em> parameter.</p></div><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.13: </span>Added the <em>cleanup_socket</em> parameter.</p></div></dd></dl>
<section id="streamreader"><h2>StreamReader<a class="headerlink" href="#streamreader" title="Link to this heading">¶</a></h2><dl class="py class"><dt class="sig sig-object py" id="asyncio.StreamReader"><em class="property"><span class="k"><span class="pre">class</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">StreamReader</span></span><a class="headerlink" href="#asyncio.StreamReader" title="Link to this definition">¶</a></dt><dd><p>Represents a reader object that provides APIs to read datafrom the IO stream. As an <a class="reference internal" href="../glossary.html#term-asynchronous-iterable"><span class="xref std std-term">asynchronous iterable</span></a>, theobject supports the <a class="reference internal" href="../reference/compound_stmts.html#async-for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></code></a> statement.</p><p>It is not recommended to instantiate <em>StreamReader</em> objectsdirectly; use <a class="reference internal" href="#asyncio.open_connection" title="asyncio.open_connection"><code class="xref py py-func docutils literal notranslate"><span class="pre">open_connection()</span></code></a> and <a class="reference internal" href="#asyncio.start_server" title="asyncio.start_server"><code class="xref py py-func docutils literal notranslate"><span class="pre">start_server()</span></code></a>instead.</p><dl class="py method"><dt class="sig sig-object py" id="asyncio.StreamReader.feed_eof"><span class="sig-name descname"><span class="pre">feed_eof</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.StreamReader.feed_eof" title="Link to this definition">¶</a></dt><dd><p>Acknowledge the EOF.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.StreamReader.read"><em class="property"><span class="k"><span class="pre">async</span></span><span class="w"> </span></em><span class="sig-name descname"><span class="pre">read</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">n</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">-1</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.StreamReader.read" title="Link to this definition">¶</a></dt><dd><p>Read up to <em>n</em> bytes from the stream.</p><p>If <em>n</em> is not provided or set to <code class="docutils literal notranslate"><span class="pre">-1</span></code>,read until EOF, then return all read <a class="reference internal" href="stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a>.If EOF was received and the internal buffer is empty,return an empty <code class="docutils literal notranslate"><span class="pre">bytes</span></code> object.</p><p>If <em>n</em> is <code class="docutils literal notranslate"><span class="pre">0</span></code>, return an empty <code class="docutils literal notranslate"><span class="pre">bytes</span></code> object immediately.</p><p>If <em>n</em> is positive, return at most <em>n</em> available <code class="docutils literal notranslate"><span class="pre">bytes</span></code>as soon as at least 1 byte is available in the internal buffer.If EOF is received before any byte is read, return an empty<code class="docutils literal notranslate"><span class="pre">bytes</span></code> object.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.StreamReader.readline"><em class="property"><span class="k"><span class="pre">async</span></span><span class="w"> </span></em><span class="sig-name descname"><span class="pre">readline</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.StreamReader.readline" title="Link to this definition">¶</a></dt><dd><p>Read one line, where “line” is a sequence of bytesending with <code class="docutils literal notranslate"><span class="pre">\n</span></code>.</p><p>If EOF is received and <code class="docutils literal notranslate"><span class="pre">\n</span></code> was not found, the methodreturns partially read data.</p><p>If EOF is received and the internal buffer is empty,return an empty <code class="docutils literal notranslate"><span class="pre">bytes</span></code> object.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.StreamReader.readexactly"><em class="property"><span class="k"><span class="pre">async</span></span><span class="w"> </span></em><span class="sig-name descname"><span class="pre">readexactly</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">n</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.StreamReader.readexactly" title="Link to this definition">¶</a></dt><dd><p>Read exactly <em>n</em> bytes.</p><p>Raise an <a class="reference internal" href="asyncio-exceptions.html#asyncio.IncompleteReadError" title="asyncio.IncompleteReadError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IncompleteReadError</span></code></a> if EOF is reached before <em>n</em>can be read. Use the <a class="reference internal" href="asyncio-exceptions.html#asyncio.IncompleteReadError.partial" title="asyncio.IncompleteReadError.partial"><code class="xref py py-attr docutils literal notranslate"><span class="pre">IncompleteReadError.partial</span></code></a>attribute to get the partially read data.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.StreamReader.readuntil"><em class="property"><span class="k"><span class="pre">async</span></span><span class="w"> </span></em><span class="sig-name descname"><span class="pre">readuntil</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">separator</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">b'\n'</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.StreamReader.readuntil" title="Link to this definition">¶</a></dt><dd><p>Read data from the stream until <em>separator</em> is found.</p><p>On success, the data and separator will be removed from theinternal buffer (consumed). Returned data will include theseparator at the end.</p><p>If the amount of data read exceeds the configured stream limit, a<a class="reference internal" href="asyncio-exceptions.html#asyncio.LimitOverrunError" title="asyncio.LimitOverrunError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">LimitOverrunError</span></code></a> exception is raised, and the datais left in the internal buffer and can be read again.</p><p>If EOF is reached before the complete separator is found,an <a class="reference internal" href="asyncio-exceptions.html#asyncio.IncompleteReadError" title="asyncio.IncompleteReadError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IncompleteReadError</span></code></a> exception is raised, and the internalbuffer is reset. The <a class="reference internal" href="asyncio-exceptions.html#asyncio.IncompleteReadError.partial" title="asyncio.IncompleteReadError.partial"><code class="xref py py-attr docutils literal notranslate"><span class="pre">IncompleteReadError.partial</span></code></a> attributemay contain a portion of the separator.</p><p>The <em>separator</em> may also be a tuple of separators. In thiscase the return value will be the shortest possible that has anyseparator as the suffix. For the purposes of <a class="reference internal" href="asyncio-exceptions.html#asyncio.LimitOverrunError" title="asyncio.LimitOverrunError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">LimitOverrunError</span></code></a>,the shortest possible separator is considered to be the one thatmatched.</p><div class="versionadded"><p><span class="versionmodified added">Added in version 3.5.2.</span></p></div><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.13: </span>The <em>separator</em> parameter may now be a <a class="reference internal" href="stdtypes.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a> ofseparators.</p></div></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.StreamReader.at_eof"><span class="sig-name descname"><span class="pre">at_eof</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.StreamReader.at_eof" title="Link to this definition">¶</a></dt><dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the buffer is empty and <a class="reference internal" href="#asyncio.StreamReader.feed_eof" title="asyncio.StreamReader.feed_eof"><code class="xref py py-meth docutils literal notranslate"><span class="pre">feed_eof()</span></code></a>was called.</p></dd></dl>
</dd></dl>
</section><section id="streamwriter"><h2>StreamWriter<a class="headerlink" href="#streamwriter" title="Link to this heading">¶</a></h2><dl class="py class"><dt class="sig sig-object py" id="asyncio.StreamWriter"><em class="property"><span class="k"><span class="pre">class</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">StreamWriter</span></span><a class="headerlink" href="#asyncio.StreamWriter" title="Link to this definition">¶</a></dt><dd><p>Represents a writer object that provides APIs to write datato the IO stream.</p><p>It is not recommended to instantiate <em>StreamWriter</em> objectsdirectly; use <a class="reference internal" href="#asyncio.open_connection" title="asyncio.open_connection"><code class="xref py py-func docutils literal notranslate"><span class="pre">open_connection()</span></code></a> and <a class="reference internal" href="#asyncio.start_server" title="asyncio.start_server"><code class="xref py py-func docutils literal notranslate"><span class="pre">start_server()</span></code></a>instead.</p><dl class="py method"><dt class="sig sig-object py" id="asyncio.StreamWriter.write"><span class="sig-name descname"><span class="pre">write</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">data</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.StreamWriter.write" title="Link to this definition">¶</a></dt><dd><p>The method attempts to write the <em>data</em> to the underlying socket immediately.If that fails, the data is queued in an internal write buffer until it can besent.</p><p>The <em>data</em> buffer should be a bytes, bytearray, or C-contiguous one-dimensionalmemoryview object.</p><p>The method should be used along with the <code class="docutils literal notranslate"><span class="pre">drain()</span></code> method:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">stream</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">data</span><span class="p">)</span><span class="k">await</span> <span class="n">stream</span><span class="o">.</span><span class="n">drain</span><span class="p">()</span></pre></div></div></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.StreamWriter.writelines"><span class="sig-name descname"><span class="pre">writelines</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">data</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.StreamWriter.writelines" title="Link to this definition">¶</a></dt><dd><p>The method writes a list (or any iterable) of bytes to the underlying socketimmediately.If that fails, the data is queued in an internal write buffer until it can besent.</p><p>The method should be used along with the <code class="docutils literal notranslate"><span class="pre">drain()</span></code> method:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">stream</span><span class="o">.</span><span class="n">writelines</span><span class="p">(</span><span class="n">lines</span><span class="p">)</span><span class="k">await</span> <span class="n">stream</span><span class="o">.</span><span class="n">drain</span><span class="p">()</span></pre></div></div></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.StreamWriter.close"><span class="sig-name descname"><span class="pre">close</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.StreamWriter.close" title="Link to this definition">¶</a></dt><dd><p>The method closes the stream and the underlying socket.</p><p>The method should be used, though not mandatory,along with the <code class="docutils literal notranslate"><span class="pre">wait_closed()</span></code> method:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">stream</span><span class="o">.</span><span class="n">close</span><span class="p">()</span><span class="k">await</span> <span class="n">stream</span><span class="o">.</span><span class="n">wait_closed</span><span class="p">()</span></pre></div></div></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.StreamWriter.can_write_eof"><span class="sig-name descname"><span class="pre">can_write_eof</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.StreamWriter.can_write_eof" title="Link to this definition">¶</a></dt><dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the underlying transport supportsthe <a class="reference internal" href="#asyncio.StreamWriter.write_eof" title="asyncio.StreamWriter.write_eof"><code class="xref py py-meth docutils literal notranslate"><span class="pre">write_eof()</span></code></a> method, <code class="docutils literal notranslate"><span class="pre">False</span></code> otherwise.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.StreamWriter.write_eof"><span class="sig-name descname"><span class="pre">write_eof</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.StreamWriter.write_eof" title="Link to this definition">¶</a></dt><dd><p>Close the write end of the stream after the buffered writedata is flushed.</p></dd></dl>
<dl class="py attribute"><dt class="sig sig-object py" id="asyncio.StreamWriter.transport"><span class="sig-name descname"><span class="pre">transport</span></span><a class="headerlink" href="#asyncio.StreamWriter.transport" title="Link to this definition">¶</a></dt><dd><p>Return the underlying asyncio transport.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.StreamWriter.get_extra_info"><span class="sig-name descname"><span class="pre">get_extra_info</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">name</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">default</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.StreamWriter.get_extra_info" title="Link to this definition">¶</a></dt><dd><p>Access optional transport information; see<a class="reference internal" href="asyncio-protocol.html#asyncio.BaseTransport.get_extra_info" title="asyncio.BaseTransport.get_extra_info"><code class="xref py py-meth docutils literal notranslate"><span class="pre">BaseTransport.get_extra_info()</span></code></a> for details.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.StreamWriter.drain"><em class="property"><span class="k"><span class="pre">async</span></span><span class="w"> </span></em><span class="sig-name descname"><span class="pre">drain</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.StreamWriter.drain" title="Link to this definition">¶</a></dt><dd><p>Wait until it is appropriate to resume writing to the stream.Example:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">writer</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">data</span><span class="p">)</span><span class="k">await</span> <span class="n">writer</span><span class="o">.</span><span class="n">drain</span><span class="p">()</span></pre></div></div><p>This is a flow control method that interacts with the underlyingIO write buffer. When the size of the buffer reachesthe high watermark, <em>drain()</em> blocks until the size of thebuffer is drained down to the low watermark and writing canbe resumed. When there is nothing to wait for, the <code class="xref py py-meth docutils literal notranslate"><span class="pre">drain()</span></code>returns immediately.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.StreamWriter.start_tls"><em class="property"><span class="k"><span class="pre">async</span></span><span class="w"> </span></em><span class="sig-name descname"><span class="pre">start_tls</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">sslcontext</span></span></em>, <em class="sig-param"><span class="keyword-only-separator o"><abbr title="Keyword-only parameters separator (PEP 3102)"><span class="pre">*</span></abbr></span></em>, <em class="sig-param"><span class="n"><span class="pre">server_hostname</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">ssl_handshake_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">ssl_shutdown_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.StreamWriter.start_tls" title="Link to this definition">¶</a></dt><dd><p>Upgrade an existing stream-based connection to TLS.</p><p>Parameters:</p><ul class="simple"><li><p><em>sslcontext</em>: a configured instance of <a class="reference internal" href="ssl.html#ssl.SSLContext" title="ssl.SSLContext"><code class="xref py py-class docutils literal notranslate"><span class="pre">SSLContext</span></code></a>.</p></li><li><p><em>server_hostname</em>: sets or overrides the host name that the targetserver’s certificate will be matched against.</p></li><li><p><em>ssl_handshake_timeout</em> is the time in seconds to wait for the TLShandshake to complete before aborting the connection. <code class="docutils literal notranslate"><span class="pre">60.0</span></code> secondsif <code class="docutils literal notranslate"><span class="pre">None</span></code> (default).</p></li><li><p><em>ssl_shutdown_timeout</em> is the time in seconds to wait for the SSL shutdownto complete before aborting the connection. <code class="docutils literal notranslate"><span class="pre">30.0</span></code> seconds if <code class="docutils literal notranslate"><span class="pre">None</span></code>(default).</p></li></ul><div class="versionadded"><p><span class="versionmodified added">Added in version 3.11.</span></p></div><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.12: </span>Added the <em>ssl_shutdown_timeout</em> parameter.</p></div></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.StreamWriter.is_closing"><span class="sig-name descname"><span class="pre">is_closing</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.StreamWriter.is_closing" title="Link to this definition">¶</a></dt><dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the stream is closed or in the process ofbeing closed.</p><div class="versionadded"><p><span class="versionmodified added">Added in version 3.7.</span></p></div></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.StreamWriter.wait_closed"><em class="property"><span class="k"><span class="pre">async</span></span><span class="w"> </span></em><span class="sig-name descname"><span class="pre">wait_closed</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.StreamWriter.wait_closed" title="Link to this definition">¶</a></dt><dd><p>Wait until the stream is closed.</p><p>Should be called after <a class="reference internal" href="#asyncio.StreamWriter.close" title="asyncio.StreamWriter.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a> to wait until the underlyingconnection is closed, ensuring that all data has been flushedbefore e.g. exiting the program.</p><div class="versionadded"><p><span class="versionmodified added">Added in version 3.7.</span></p></div></dd></dl>
</dd></dl>
</section><section id="examples"><h2>Examples<a class="headerlink" href="#examples" title="Link to this heading">¶</a></h2><section id="tcp-echo-client-using-streams"><span id="asyncio-tcp-echo-client-streams"></span><h3>TCP echo client using streams<a class="headerlink" href="#tcp-echo-client-using-streams" title="Link to this heading">¶</a></h3><p>TCP echo client using the <a class="reference internal" href="#asyncio.open_connection" title="asyncio.open_connection"><code class="xref py py-func docutils literal notranslate"><span class="pre">asyncio.open_connection()</span></code></a> function:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span><span class="w"> </span><span class="nn">asyncio</span>
<span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">tcp_echo_client</span><span class="p">(</span><span class="n">message</span><span class="p">):</span> <span class="n">reader</span><span class="p">,</span> <span class="n">writer</span> <span class="o">=</span> <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">open_connection</span><span class="p">(</span> <span class="s1">'127.0.0.1'</span><span class="p">,</span> <span class="mi">8888</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">'Send: </span><span class="si">{</span><span class="n">message</span><span class="si">!r}</span><span class="s1">'</span><span class="p">)</span> <span class="n">writer</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">message</span><span class="o">.</span><span class="n">encode</span><span class="p">())</span> <span class="k">await</span> <span class="n">writer</span><span class="o">.</span><span class="n">drain</span><span class="p">()</span>
<span class="n">data</span> <span class="o">=</span> <span class="k">await</span> <span class="n">reader</span><span class="o">.</span><span class="n">read</span><span class="p">(</span><span class="mi">100</span><span class="p">)</span> <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">'Received: </span><span class="si">{</span><span class="n">data</span><span class="o">.</span><span class="n">decode</span><span class="p">()</span><span class="si">!r}</span><span class="s1">'</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">'Close the connection'</span><span class="p">)</span> <span class="n">writer</span><span class="o">.</span><span class="n">close</span><span class="p">()</span> <span class="k">await</span> <span class="n">writer</span><span class="o">.</span><span class="n">wait_closed</span><span class="p">()</span>
<span class="n">asyncio</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="n">tcp_echo_client</span><span class="p">(</span><span class="s1">'Hello World!'</span><span class="p">))</span></pre></div></div><div class="admonition seealso"><p class="admonition-title">See also</p><p>The <a class="reference internal" href="asyncio-protocol.html#asyncio-example-tcp-echo-client-protocol"><span class="std std-ref">TCP echo client protocol</span></a>example uses the low-level <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.create_connection" title="asyncio.loop.create_connection"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.create_connection()</span></code></a> method.</p></div></section><section id="tcp-echo-server-using-streams"><span id="asyncio-tcp-echo-server-streams"></span><h3>TCP echo server using streams<a class="headerlink" href="#tcp-echo-server-using-streams" title="Link to this heading">¶</a></h3><p>TCP echo server using the <a class="reference internal" href="#asyncio.start_server" title="asyncio.start_server"><code class="xref py py-func docutils literal notranslate"><span class="pre">asyncio.start_server()</span></code></a> function:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span><span class="w"> </span><span class="nn">asyncio</span>
<span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">handle_echo</span><span class="p">(</span><span class="n">reader</span><span class="p">,</span> <span class="n">writer</span><span class="p">):</span> <span class="n">data</span> <span class="o">=</span> <span class="k">await</span> <span class="n">reader</span><span class="o">.</span><span class="n">read</span><span class="p">(</span><span class="mi">100</span><span class="p">)</span> <span class="n">message</span> <span class="o">=</span> <span class="n">data</span><span class="o">.</span><span class="n">decode</span><span class="p">()</span> <span class="n">addr</span> <span class="o">=</span> <span class="n">writer</span><span class="o">.</span><span class="n">get_extra_info</span><span class="p">(</span><span class="s1">'peername'</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">"Received </span><span class="si">{</span><span class="n">message</span><span class="si">!r}</span><span class="s2"> from </span><span class="si">{</span><span class="n">addr</span><span class="si">!r}</span><span class="s2">"</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">"Send: </span><span class="si">{</span><span class="n">message</span><span class="si">!r}</span><span class="s2">"</span><span class="p">)</span> <span class="n">writer</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">data</span><span class="p">)</span> <span class="k">await</span> <span class="n">writer</span><span class="o">.</span><span class="n">drain</span><span class="p">()</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"Close the connection"</span><span class="p">)</span> <span class="n">writer</span><span class="o">.</span><span class="n">close</span><span class="p">()</span> <span class="k">await</span> <span class="n">writer</span><span class="o">.</span><span class="n">wait_closed</span><span class="p">()</span>
<span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">main</span><span class="p">():</span> <span class="n">server</span> <span class="o">=</span> <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">start_server</span><span class="p">(</span> <span class="n">handle_echo</span><span class="p">,</span> <span class="s1">'127.0.0.1'</span><span class="p">,</span> <span class="mi">8888</span><span class="p">)</span>
<span class="n">addrs</span> <span class="o">=</span> <span class="s1">', '</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="nb">str</span><span class="p">(</span><span class="n">sock</span><span class="o">.</span><span class="n">getsockname</span><span class="p">())</span> <span class="k">for</span> <span class="n">sock</span> <span class="ow">in</span> <span class="n">server</span><span class="o">.</span><span class="n">sockets</span><span class="p">)</span> <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">'Serving on </span><span class="si">{</span><span class="n">addrs</span><span class="si">}</span><span class="s1">'</span><span class="p">)</span>
<span class="k">async</span> <span class="k">with</span> <span class="n">server</span><span class="p">:</span> <span class="k">await</span> <span class="n">server</span><span class="o">.</span><span class="n">serve_forever</span><span class="p">()</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></pre></div></div><div class="admonition seealso"><p class="admonition-title">See also</p><p>The <a class="reference internal" href="asyncio-protocol.html#asyncio-example-tcp-echo-server-protocol"><span class="std std-ref">TCP echo server protocol</span></a>example uses the <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.create_server" title="asyncio.loop.create_server"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.create_server()</span></code></a> method.</p></div></section><section id="get-http-headers"><h3>Get HTTP headers<a class="headerlink" href="#get-http-headers" title="Link to this heading">¶</a></h3><p>Simple example querying HTTP headers of the URL passed on the command line:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span><span class="w"> </span><span class="nn">asyncio</span><span class="kn">import</span><span class="w"> </span><span class="nn">urllib.parse</span><span class="kn">import</span><span class="w"> </span><span class="nn">sys</span>
<span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">print_http_headers</span><span class="p">(</span><span class="n">url</span><span class="p">):</span> <span class="n">url</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">parse</span><span class="o">.</span><span class="n">urlsplit</span><span class="p">(</span><span class="n">url</span><span class="p">)</span> <span class="k">if</span> <span class="n">url</span><span class="o">.</span><span class="n">scheme</span> <span class="o">==</span> <span class="s1">'https'</span><span class="p">:</span> <span class="n">reader</span><span class="p">,</span> <span class="n">writer</span> <span class="o">=</span> <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">open_connection</span><span class="p">(</span> <span class="n">url</span><span class="o">.</span><span class="n">hostname</span><span class="p">,</span> <span class="mi">443</span><span class="p">,</span> <span class="n">ssl</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span> <span class="k">else</span><span class="p">:</span> <span class="n">reader</span><span class="p">,</span> <span class="n">writer</span> <span class="o">=</span> <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">open_connection</span><span class="p">(</span> <span class="n">url</span><span class="o">.</span><span class="n">hostname</span><span class="p">,</span> <span class="mi">80</span><span class="p">)</span>
<span class="n">query</span> <span class="o">=</span> <span class="p">(</span> <span class="sa">f</span><span class="s2">"HEAD </span><span class="si">{</span><span class="n">url</span><span class="o">.</span><span class="n">path</span><span class="w"> </span><span class="ow">or</span><span class="w"> </span><span class="s1">'/'</span><span class="si">}</span><span class="s2"> HTTP/1.0</span><span class="se">\r\n</span><span class="s2">"</span> <span class="sa">f</span><span class="s2">"Host: </span><span class="si">{</span><span class="n">url</span><span class="o">.</span><span class="n">hostname</span><span class="si">}</span><span class="se">\r\n</span><span class="s2">"</span> <span class="sa">f</span><span class="s2">"</span><span class="se">\r\n</span><span class="s2">"</span> <span class="p">)</span>
<span class="n">writer</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">query</span><span class="o">.</span><span class="n">encode</span><span class="p">(</span><span class="s1">'latin-1'</span><span class="p">))</span> <span class="k">while</span> <span class="kc">True</span><span class="p">:</span> <span class="n">line</span> <span class="o">=</span> <span class="k">await</span> <span class="n">reader</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span> <span class="k">if</span> <span class="ow">not</span> <span class="n">line</span><span class="p">:</span> <span class="k">break</span>
<span class="n">line</span> <span class="o">=</span> <span class="n">line</span><span class="o">.</span><span class="n">decode</span><span class="p">(</span><span class="s1">'latin1'</span><span class="p">)</span><span class="o">.</span><span class="n">rstrip</span><span class="p">()</span> <span class="k">if</span> <span class="n">line</span><span class="p">:</span> <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">'HTTP header> </span><span class="si">{</span><span class="n">line</span><span class="si">}</span><span class="s1">'</span><span class="p">)</span>
<span class="c1"># Ignore the body, close the socket</span> <span class="n">writer</span><span class="o">.</span><span class="n">close</span><span class="p">()</span> <span class="k">await</span> <span class="n">writer</span><span class="o">.</span><span class="n">wait_closed</span><span class="p">()</span>
<span class="n">url</span> <span class="o">=</span> <span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span><span class="n">asyncio</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="n">print_http_headers</span><span class="p">(</span><span class="n">url</span><span class="p">))</span></pre></div></div><p>Usage:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="n">example</span><span class="o">.</span><span class="n">py</span> <span class="n">http</span><span class="p">:</span><span class="o">//</span><span class="n">example</span><span class="o">.</span><span class="n">com</span><span class="o">/</span><span class="n">path</span><span class="o">/</span><span class="n">page</span><span class="o">.</span><span class="n">html</span></pre></div></div><p>or with HTTPS:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="n">example</span><span class="o">.</span><span class="n">py</span> <span class="n">https</span><span class="p">:</span><span class="o">//</span><span class="n">example</span><span class="o">.</span><span class="n">com</span><span class="o">/</span><span class="n">path</span><span class="o">/</span><span class="n">page</span><span class="o">.</span><span class="n">html</span></pre></div></div></section><section id="register-an-open-socket-to-wait-for-data-using-streams"><span id="asyncio-example-create-connection-streams"></span><h3>Register an open socket to wait for data using streams<a class="headerlink" href="#register-an-open-socket-to-wait-for-data-using-streams" title="Link to this heading">¶</a></h3><p>Coroutine waiting until a socket receives data using the<a class="reference internal" href="#asyncio.open_connection" title="asyncio.open_connection"><code class="xref py py-func docutils literal notranslate"><span class="pre">open_connection()</span></code></a> function:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span><span class="w"> </span><span class="nn">asyncio</span><span class="kn">import</span><span class="w"> </span><span class="nn">socket</span>
<span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">wait_for_data</span><span class="p">():</span> <span class="c1"># Get a reference to the current event loop because</span> <span class="c1"># we want to access low-level APIs.</span> <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>
<span class="c1"># Create a pair of connected sockets.</span> <span class="n">rsock</span><span class="p">,</span> <span class="n">wsock</span> <span class="o">=</span> <span class="n">socket</span><span class="o">.</span><span class="n">socketpair</span><span class="p">()</span>
<span class="c1"># Register the open socket to wait for data.</span> <span class="n">reader</span><span class="p">,</span> <span class="n">writer</span> <span class="o">=</span> <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">open_connection</span><span class="p">(</span><span class="n">sock</span><span class="o">=</span><span class="n">rsock</span><span class="p">)</span>
<span class="c1"># Simulate the reception of data from the network</span> <span class="n">loop</span><span class="o">.</span><span class="n">call_soon</span><span class="p">(</span><span class="n">wsock</span><span class="o">.</span><span class="n">send</span><span class="p">,</span> <span class="s1">'abc'</span><span class="o">.</span><span class="n">encode</span><span class="p">())</span>
<span class="c1"># Wait for data</span> <span class="n">data</span> <span class="o">=</span> <span class="k">await</span> <span class="n">reader</span><span class="o">.</span><span class="n">read</span><span class="p">(</span><span class="mi">100</span><span class="p">)</span>
<span class="c1"># Got data, we are done: close the socket</span> <span class="nb">print</span><span class="p">(</span><span class="s2">"Received:"</span><span class="p">,</span> <span class="n">data</span><span class="o">.</span><span class="n">decode</span><span class="p">())</span> <span class="n">writer</span><span class="o">.</span><span class="n">close</span><span class="p">()</span> <span class="k">await</span> <span class="n">writer</span><span class="o">.</span><span class="n">wait_closed</span><span class="p">()</span>
<span class="c1"># Close the second socket</span> <span class="n">wsock</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
<span class="n">asyncio</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="n">wait_for_data</span><span class="p">())</span></pre></div></div><div class="admonition seealso"><p class="admonition-title">See also</p><p>The <a class="reference internal" href="asyncio-protocol.html#asyncio-example-create-connection"><span class="std std-ref">register an open socket to wait for data using a protocol</span></a> example uses a low-level protocol andthe <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.create_connection" title="asyncio.loop.create_connection"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.create_connection()</span></code></a> method.</p><p>The <a class="reference internal" href="asyncio-eventloop.html#asyncio-example-watch-fd"><span class="std std-ref">watch a file descriptor for read events</span></a> example uses the low-level<a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.add_reader" title="asyncio.loop.add_reader"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.add_reader()</span></code></a> method to watch a file descriptor.</p></div></section></section></section>
<div class="clearer"></div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="Main"> <div class="sphinxsidebarwrapper"> <div> <h3><a href="../contents.html">Table of Contents</a></h3> <ul><li><a class="reference internal" href="#">Streams</a><ul><li><a class="reference internal" href="#streamreader">StreamReader</a></li><li><a class="reference internal" href="#streamwriter">StreamWriter</a></li><li><a class="reference internal" href="#examples">Examples</a><ul><li><a class="reference internal" href="#tcp-echo-client-using-streams">TCP echo client using streams</a></li><li><a class="reference internal" href="#tcp-echo-server-using-streams">TCP echo server using streams</a></li><li><a class="reference internal" href="#get-http-headers">Get HTTP headers</a></li><li><a class="reference internal" href="#register-an-open-socket-to-wait-for-data-using-streams">Register an open socket to wait for data using streams</a></li></ul></li></ul></li></ul>
</div> <div> <h4>Previous topic</h4> <p class="topless"><a href="asyncio-task.html" title="previous chapter">Coroutines and Tasks</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="asyncio-sync.html" title="next chapter">Synchronization Primitives</a></p> </div> <script> document.addEventListener('DOMContentLoaded', () => { const title = document.querySelector('meta[property="og:title"]').content; const elements = document.querySelectorAll('.improvepage'); const pageurl = window.location.href.split('?')[0]; elements.forEach(element => { const url = new URL(element.href.split('?')[0].replace("-nojs", "")); url.searchParams.set('pagetitle', title); url.searchParams.set('pageurl', pageurl); url.searchParams.set('pagesource', "library/asyncio-stream.rst"); element.href = url.toString(); }); }); </script> <div role="note" aria-label="source link"> <h3>This page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a bug</a></li> <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li> <li> <a href="https://github.com/python/cpython/blob/main/Doc/library/asyncio-stream.rst?plain=1" rel="nofollow">Show source </a> </li> </ul> </div> </div><div id="sidebarbutton" title="Collapse sidebar"><span>«</span></div>
</div> <div class="clearer"></div> </div> <div class="related" role="navigation" aria-label="Related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="asyncio-sync.html" title="Synchronization Primitives" >next</a> |</li> <li class="right" > <a href="asyncio-task.html" title="Coroutines and Tasks" >previous</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.15.0a6 Documentation</a> » </li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="ipc.html" >Networking and Interprocess Communication</a> »</li> <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> »</li> <li class="nav-item nav-item-this"><a href="">Streams</a></li> <li class="right">
<div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box"> <input type="submit" value="Go"> </form> </div> | </li> <li class="right"><label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> |</li> </ul> </div> <div class="footer"> © <a href="../copyright.html">Copyright</a> 2001 Python Software Foundation. <br> This page is licensed under the Python Software Foundation License Version 2. <br> Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. <br> See <a href="/license.html">History and License</a> for more information.<br> <br>
The Python Software Foundation is a non-profit corporation.<a href="https://www.python.org/psf/donations/">Please donate.</a><br> <br> Last updated on Mar 10, 2026 (08:58 UTC). <a href="/bugs.html">Found a bug</a>? <br>
Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3. </div>
</body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716<!DOCTYPE html>
<html lang="en" data-content_root="../"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta property="og:title" content="Subprocesses" /><meta property="og:type" content="website" /><meta property="og:url" content="https://docs.python.org/3/library/asyncio-subprocess.html" /><meta property="og:site_name" content="Python documentation" /><meta property="og:description" content="Source code: Lib/asyncio/subprocess.py, Lib/asyncio/base_subprocess.py This section describes high-level async/await asyncio APIs to create and manage subprocesses. Here’s an example of how asyncio..." /><meta property="og:image:width" content="1146" /><meta property="og:image:height" content="600" /><meta property="og:image" content="https://docs.python.org/3.15/_images/social_previews/summary_library_asyncio-subprocess_a9c60f48.png" /><meta property="og:image:alt" content="Source code: Lib/asyncio/subprocess.py, Lib/asyncio/base_subprocess.py This section describes high-level async/await asyncio APIs to create and manage subprocesses. Here’s an example of how asyncio..." /><meta name="description" content="Source code: Lib/asyncio/subprocess.py, Lib/asyncio/base_subprocess.py This section describes high-level async/await asyncio APIs to create and manage subprocesses. Here’s an example of how asyncio..." /><meta name="twitter:card" content="summary_large_image" /><meta name="theme-color" content="#3776ab">
<title>Subprocesses — Python 3.15.0a6 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" /> <link rel="stylesheet" type="text/css" href="../_static/classic.css?v=234b1a7c" /> <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=89a2f22a" /> <link rel="stylesheet" type="text/css" href="../_static/profiling-sampling-visualization.css?v=0c2600ae" /> <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" /> <script src="../_static/documentation_options.js?v=6b7c9ff5"></script> <script src="../_static/doctools.js?v=9bcbadda"></script> <script src="../_static/sphinx_highlight.js?v=dc90522c"></script> <script src="../_static/profiling-sampling-visualization.js?v=9811ed04"></script> <script src="../_static/sidebar.js"></script> <link rel="search" type="application/opensearchdescription+xml" title="Search within Python 3.15.0a6 documentation" href="../_static/opensearch.xml"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="copyright" title="Copyright" href="../copyright.html" /> <link rel="next" title="Queues" href="asyncio-queue.html" /> <link rel="prev" title="Synchronization Primitives" href="asyncio-sync.html" /> <script defer file-types="bz2,epub,zip" data-domain="docs.python.org" src="https://analytics.python.org/js/script.file-downloads.outbound-links.js"></script> <link rel="canonical" href="https://docs.python.org/3/library/asyncio-subprocess.html">
<style> @media only screen { table.full-width-table { width: 100%; } } </style><link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css"> <link rel="shortcut icon" type="image/png" href="../_static/py.svg"> <script type="text/javascript" src="../_static/copybutton.js"></script> <script type="text/javascript" src="../_static/menu.js"></script> <script type="text/javascript" src="../_static/search-focus.js"></script> <script type="text/javascript" src="../_static/themetoggle.js"></script> <script type="text/javascript" src="../_static/rtd_switcher.js"></script> <meta name="readthedocs-addons-api-version" content="1">
</head><body><div class="mobile-nav"> <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation" aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu"> <nav class="nav-content" role="navigation"> <label for="menuToggler" class="toggler__label"> <span></span> </label> <span class="nav-items-wrapper"> <a href="https://www.python.org/" class="nav-logo"> <img src="../_static/py.svg" alt="Python logo"> </a> <span class="version_switcher_placeholder"></span> <form role="search" class="search" action="../search.html" method="get"> <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon"> <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> </svg> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q"> <input type="submit" value="Go"> </form> </span> </nav> <div class="menu-wrapper"> <nav class="menu" role="navigation" aria-label="main navigation"> <div class="language_switcher_placeholder"></div> <label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> <div> <h3><a href="../contents.html">Table of Contents</a></h3> <ul><li><a class="reference internal" href="#">Subprocesses</a><ul><li><a class="reference internal" href="#creating-subprocesses">Creating Subprocesses</a></li><li><a class="reference internal" href="#constants">Constants</a></li><li><a class="reference internal" href="#interacting-with-subprocesses">Interacting with Subprocesses</a><ul><li><a class="reference internal" href="#subprocess-and-threads">Subprocess and Threads</a></li><li><a class="reference internal" href="#examples">Examples</a></li></ul></li></ul></li></ul>
</div> <div> <h4>Previous topic</h4> <p class="topless"><a href="asyncio-sync.html" title="previous chapter">Synchronization Primitives</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="asyncio-queue.html" title="next chapter">Queues</a></p> </div> <script> document.addEventListener('DOMContentLoaded', () => { const title = document.querySelector('meta[property="og:title"]').content; const elements = document.querySelectorAll('.improvepage'); const pageurl = window.location.href.split('?')[0]; elements.forEach(element => { const url = new URL(element.href.split('?')[0].replace("-nojs", "")); url.searchParams.set('pagetitle', title); url.searchParams.set('pageurl', pageurl); url.searchParams.set('pagesource', "library/asyncio-subprocess.rst"); element.href = url.toString(); }); }); </script> <div role="note" aria-label="source link"> <h3>This page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a bug</a></li> <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li> <li> <a href="https://github.com/python/cpython/blob/main/Doc/library/asyncio-subprocess.rst?plain=1" rel="nofollow">Show source </a> </li> </ul> </div> </nav> </div></div>
<div class="related" role="navigation" aria-label="Related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="asyncio-queue.html" title="Queues" accesskey="N">next</a> |</li> <li class="right" > <a href="asyncio-sync.html" title="Synchronization Primitives" accesskey="P">previous</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.15.0a6 Documentation</a> » </li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="ipc.html" >Networking and Interprocess Communication</a> »</li> <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> »</li> <li class="nav-item nav-item-this"><a href="">Subprocesses</a></li> <li class="right">
<div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box"> <input type="submit" value="Go"> </form> </div> | </li> <li class="right"><label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> |</li> </ul> </div>
<div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <section id="subprocesses"><span id="asyncio-subprocess"></span><h1>Subprocesses<a class="headerlink" href="#subprocesses" title="Link to this heading">¶</a></h1><p><strong>Source code:</strong> <a class="extlink-source reference external" href="https://github.com/python/cpython/tree/main/Lib/asyncio/subprocess.py">Lib/asyncio/subprocess.py</a>,<a class="extlink-source reference external" href="https://github.com/python/cpython/tree/main/Lib/asyncio/base_subprocess.py">Lib/asyncio/base_subprocess.py</a></p><hr class="docutils" /><p>This section describes high-level async/await asyncio APIs tocreate and manage subprocesses.</p><p id="asyncio-example-subprocess-shell">Here’s an example of how asyncio can run a shell command andobtain its result:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span><span class="w"> </span><span class="nn">asyncio</span>
<span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">run</span><span class="p">(</span><span class="n">cmd</span><span class="p">):</span> <span class="n">proc</span> <span class="o">=</span> <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">create_subprocess_shell</span><span class="p">(</span> <span class="n">cmd</span><span class="p">,</span> <span class="n">stdout</span><span class="o">=</span><span class="n">asyncio</span><span class="o">.</span><span class="n">subprocess</span><span class="o">.</span><span class="n">PIPE</span><span class="p">,</span> <span class="n">stderr</span><span class="o">=</span><span class="n">asyncio</span><span class="o">.</span><span class="n">subprocess</span><span class="o">.</span><span class="n">PIPE</span><span class="p">)</span>
<span class="n">stdout</span><span class="p">,</span> <span class="n">stderr</span> <span class="o">=</span> <span class="k">await</span> <span class="n">proc</span><span class="o">.</span><span class="n">communicate</span><span class="p">()</span>
<span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">'[</span><span class="si">{</span><span class="n">cmd</span><span class="si">!r}</span><span class="s1"> exited with </span><span class="si">{</span><span class="n">proc</span><span class="o">.</span><span class="n">returncode</span><span class="si">}</span><span class="s1">]'</span><span class="p">)</span> <span class="k">if</span> <span class="n">stdout</span><span class="p">:</span> <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">'[stdout]</span><span class="se">\n</span><span class="si">{</span><span class="n">stdout</span><span class="o">.</span><span class="n">decode</span><span class="p">()</span><span class="si">}</span><span class="s1">'</span><span class="p">)</span> <span class="k">if</span> <span class="n">stderr</span><span class="p">:</span> <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">'[stderr]</span><span class="se">\n</span><span class="si">{</span><span class="n">stderr</span><span class="o">.</span><span class="n">decode</span><span class="p">()</span><span class="si">}</span><span class="s1">'</span><span class="p">)</span>
<span class="n">asyncio</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="n">run</span><span class="p">(</span><span class="s1">'ls /zzz'</span><span class="p">))</span></pre></div></div><p>will print:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="p">[</span><span class="s1">'ls /zzz'</span> <span class="n">exited</span> <span class="k">with</span> <span class="mi">1</span><span class="p">]</span><span class="p">[</span><span class="n">stderr</span><span class="p">]</span><span class="n">ls</span><span class="p">:</span> <span class="o">/</span><span class="n">zzz</span><span class="p">:</span> <span class="n">No</span> <span class="n">such</span> <span class="n">file</span> <span class="ow">or</span> <span class="n">directory</span></pre></div></div><p>Because all asyncio subprocess functions are asynchronous and asyncioprovides many tools to work with such functions, it is easy to executeand monitor multiple subprocesses in parallel. It is indeed trivialto modify the above example to run several commands simultaneously:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">main</span><span class="p">():</span> <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">gather</span><span class="p">(</span> <span class="n">run</span><span class="p">(</span><span class="s1">'ls /zzz'</span><span class="p">),</span> <span class="n">run</span><span class="p">(</span><span class="s1">'sleep 1; echo "hello"'</span><span class="p">))</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></pre></div></div><p>See also the <a class="reference internal" href="#examples">Examples</a> subsection.</p><section id="creating-subprocesses"><h2>Creating Subprocesses<a class="headerlink" href="#creating-subprocesses" title="Link to this heading">¶</a></h2><dl class="py function"><dt class="sig sig-object py" id="asyncio.create_subprocess_exec"><em class="property"><span class="k"><span class="pre">async</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">create_subprocess_exec</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">program</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="n"><span class="pre">stdin</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">stdout</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">stderr</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">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="o"><span class="pre">**</span></span><span class="n"><span class="pre">kwds</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.create_subprocess_exec" title="Link to this definition">¶</a></dt><dd><p>Create a subprocess.</p><p>The <em>limit</em> argument sets the buffer limit for <a class="reference internal" href="asyncio-stream.html#asyncio.StreamReader" title="asyncio.StreamReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamReader</span></code></a>wrappers for <a class="reference internal" href="#asyncio.subprocess.Process.stdout" title="asyncio.subprocess.Process.stdout"><code class="xref py py-attr docutils literal notranslate"><span class="pre">stdout</span></code></a> and <a class="reference internal" href="#asyncio.subprocess.Process.stderr" title="asyncio.subprocess.Process.stderr"><code class="xref py py-attr docutils literal notranslate"><span class="pre">stderr</span></code></a>(if <a class="reference internal" href="subprocess.html#subprocess.PIPE" title="subprocess.PIPE"><code class="xref py py-const docutils literal notranslate"><span class="pre">subprocess.PIPE</span></code></a> is passed to <em>stdout</em> and <em>stderr</em> arguments).</p><p>Return a <a class="reference internal" href="#asyncio.subprocess.Process" title="asyncio.subprocess.Process"><code class="xref py py-class docutils literal notranslate"><span class="pre">Process</span></code></a> instance.</p><p>See the documentation of <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.subprocess_exec" title="asyncio.loop.subprocess_exec"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.subprocess_exec()</span></code></a> for otherparameters.</p><p>If the process object is garbage collected while the process is stillrunning, the child process will be killed.</p><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.10: </span>Removed the <em>loop</em> parameter.</p></div></dd></dl>
<dl class="py function"><dt class="sig sig-object py" id="asyncio.create_subprocess_shell"><em class="property"><span class="k"><span class="pre">async</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">create_subprocess_shell</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">cmd</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">stdin</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">stdout</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">stderr</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">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="o"><span class="pre">**</span></span><span class="n"><span class="pre">kwds</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.create_subprocess_shell" title="Link to this definition">¶</a></dt><dd><p>Run the <em>cmd</em> shell command.</p><p>The <em>limit</em> argument sets the buffer limit for <a class="reference internal" href="asyncio-stream.html#asyncio.StreamReader" title="asyncio.StreamReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamReader</span></code></a>wrappers for <a class="reference internal" href="#asyncio.subprocess.Process.stdout" title="asyncio.subprocess.Process.stdout"><code class="xref py py-attr docutils literal notranslate"><span class="pre">stdout</span></code></a> and <a class="reference internal" href="#asyncio.subprocess.Process.stderr" title="asyncio.subprocess.Process.stderr"><code class="xref py py-attr docutils literal notranslate"><span class="pre">stderr</span></code></a>(if <a class="reference internal" href="subprocess.html#subprocess.PIPE" title="subprocess.PIPE"><code class="xref py py-const docutils literal notranslate"><span class="pre">subprocess.PIPE</span></code></a> is passed to <em>stdout</em> and <em>stderr</em> arguments).</p><p>Return a <a class="reference internal" href="#asyncio.subprocess.Process" title="asyncio.subprocess.Process"><code class="xref py py-class docutils literal notranslate"><span class="pre">Process</span></code></a> instance.</p><p>See the documentation of <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.subprocess_shell" title="asyncio.loop.subprocess_shell"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.subprocess_shell()</span></code></a> for otherparameters.</p><p>If the process object is garbage collected while the process is stillrunning, the child process will be killed.</p><div class="admonition important"><p class="admonition-title">Important</p><p>It is the application’s responsibility to ensure that all whitespace andspecial characters are quoted appropriately to avoid <a class="reference external" href="https://en.wikipedia.org/wiki/Shell_injection#Shell_injection">shell injection</a>vulnerabilities. The <a class="reference internal" href="shlex.html#shlex.quote" title="shlex.quote"><code class="xref py py-func docutils literal notranslate"><span class="pre">shlex.quote()</span></code></a> function can be used to properlyescape whitespace and special shell characters in strings that are goingto be used to construct shell commands.</p></div><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.10: </span>Removed the <em>loop</em> parameter.</p></div></dd></dl>
<div class="admonition note"><p class="admonition-title">Note</p><p>Subprocesses are available for Windows if a <a class="reference internal" href="asyncio-eventloop.html#asyncio.ProactorEventLoop" title="asyncio.ProactorEventLoop"><code class="xref py py-class docutils literal notranslate"><span class="pre">ProactorEventLoop</span></code></a> isused. See <a class="reference internal" href="asyncio-platforms.html#asyncio-windows-subprocess"><span class="std std-ref">Subprocess Support on Windows</span></a>for details.</p></div><div class="admonition seealso"><p class="admonition-title">See also</p><p>asyncio also has the following <em>low-level</em> APIs to work with subprocesses:<a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.subprocess_exec" title="asyncio.loop.subprocess_exec"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.subprocess_exec()</span></code></a>, <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.subprocess_shell" title="asyncio.loop.subprocess_shell"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.subprocess_shell()</span></code></a>,<a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.connect_read_pipe" title="asyncio.loop.connect_read_pipe"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.connect_read_pipe()</span></code></a>, <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.connect_write_pipe" title="asyncio.loop.connect_write_pipe"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.connect_write_pipe()</span></code></a>,as well as the <a class="reference internal" href="asyncio-protocol.html#asyncio-subprocess-transports"><span class="std std-ref">Subprocess Transports</span></a>and <a class="reference internal" href="asyncio-protocol.html#asyncio-subprocess-protocols"><span class="std std-ref">Subprocess Protocols</span></a>.</p></div></section><section id="constants"><h2>Constants<a class="headerlink" href="#constants" title="Link to this heading">¶</a></h2><dl class="py data"><dt class="sig sig-object py" id="asyncio.subprocess.PIPE"><span class="sig-prename descclassname"><span class="pre">asyncio.subprocess.</span></span><span class="sig-name descname"><span class="pre">PIPE</span></span><a class="headerlink" href="#asyncio.subprocess.PIPE" title="Link to this definition">¶</a></dt><dd><p>Can be passed to the <em>stdin</em>, <em>stdout</em> or <em>stderr</em> parameters.</p><p>If <em>PIPE</em> is passed to <em>stdin</em> argument, the<a class="reference internal" href="#asyncio.subprocess.Process.stdin" title="asyncio.subprocess.Process.stdin"><code class="xref py py-attr docutils literal notranslate"><span class="pre">Process.stdin</span></code></a> attributewill point to a <a class="reference internal" href="asyncio-stream.html#asyncio.StreamWriter" title="asyncio.StreamWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamWriter</span></code></a> instance.</p><p>If <em>PIPE</em> is passed to <em>stdout</em> or <em>stderr</em> arguments, the<a class="reference internal" href="#asyncio.subprocess.Process.stdout" title="asyncio.subprocess.Process.stdout"><code class="xref py py-attr docutils literal notranslate"><span class="pre">Process.stdout</span></code></a> and<a class="reference internal" href="#asyncio.subprocess.Process.stderr" title="asyncio.subprocess.Process.stderr"><code class="xref py py-attr docutils literal notranslate"><span class="pre">Process.stderr</span></code></a>attributes will point to <a class="reference internal" href="asyncio-stream.html#asyncio.StreamReader" title="asyncio.StreamReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamReader</span></code></a> instances.</p></dd></dl>
<dl class="py data"><dt class="sig sig-object py" id="asyncio.subprocess.STDOUT"><span class="sig-prename descclassname"><span class="pre">asyncio.subprocess.</span></span><span class="sig-name descname"><span class="pre">STDOUT</span></span><a class="headerlink" href="#asyncio.subprocess.STDOUT" title="Link to this definition">¶</a></dt><dd><p>Special value that can be used as the <em>stderr</em> argument and indicatesthat standard error should be redirected into standard output.</p></dd></dl>
<dl class="py data"><dt class="sig sig-object py" id="asyncio.subprocess.DEVNULL"><span class="sig-prename descclassname"><span class="pre">asyncio.subprocess.</span></span><span class="sig-name descname"><span class="pre">DEVNULL</span></span><a class="headerlink" href="#asyncio.subprocess.DEVNULL" title="Link to this definition">¶</a></dt><dd><p>Special value that can be used as the <em>stdin</em>, <em>stdout</em> or <em>stderr</em> argumentto process creation functions. It indicates that the special file<a class="reference internal" href="os.html#os.devnull" title="os.devnull"><code class="xref py py-data docutils literal notranslate"><span class="pre">os.devnull</span></code></a> will be used for the corresponding subprocess stream.</p></dd></dl>
</section><section id="interacting-with-subprocesses"><h2>Interacting with Subprocesses<a class="headerlink" href="#interacting-with-subprocesses" title="Link to this heading">¶</a></h2><p>Both <a class="reference internal" href="#asyncio.create_subprocess_exec" title="asyncio.create_subprocess_exec"><code class="xref py py-func docutils literal notranslate"><span class="pre">create_subprocess_exec()</span></code></a> and <a class="reference internal" href="#asyncio.create_subprocess_shell" title="asyncio.create_subprocess_shell"><code class="xref py py-func docutils literal notranslate"><span class="pre">create_subprocess_shell()</span></code></a>functions return instances of the <em>Process</em> class. <em>Process</em> is a high-levelwrapper that allows communicating with subprocesses and watching fortheir completion.</p><dl class="py class"><dt class="sig sig-object py" id="asyncio.subprocess.Process"><em class="property"><span class="k"><span class="pre">class</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">asyncio.subprocess.</span></span><span class="sig-name descname"><span class="pre">Process</span></span><a class="headerlink" href="#asyncio.subprocess.Process" title="Link to this definition">¶</a></dt><dd><p>An object that wraps OS processes created by the<a class="reference internal" href="#asyncio.create_subprocess_exec" title="asyncio.create_subprocess_exec"><code class="xref py py-func docutils literal notranslate"><span class="pre">create_subprocess_exec()</span></code></a> and <a class="reference internal" href="#asyncio.create_subprocess_shell" title="asyncio.create_subprocess_shell"><code class="xref py py-func docutils literal notranslate"><span class="pre">create_subprocess_shell()</span></code></a>functions.</p><p>This class is designed to have a similar API to the<a class="reference internal" href="subprocess.html#subprocess.Popen" title="subprocess.Popen"><code class="xref py py-class docutils literal notranslate"><span class="pre">subprocess.Popen</span></code></a> class, but there are somenotable differences:</p><ul class="simple"><li><p>unlike Popen, Process instances do not have an equivalent tothe <a class="reference internal" href="subprocess.html#subprocess.Popen.poll" title="subprocess.Popen.poll"><code class="xref py py-meth docutils literal notranslate"><span class="pre">poll()</span></code></a> method;</p></li><li><p>the <a class="reference internal" href="#asyncio.subprocess.Process.communicate" title="asyncio.subprocess.Process.communicate"><code class="xref py py-meth docutils literal notranslate"><span class="pre">communicate()</span></code></a> and<a class="reference internal" href="#asyncio.subprocess.Process.wait" title="asyncio.subprocess.Process.wait"><code class="xref py py-meth docutils literal notranslate"><span class="pre">wait()</span></code></a> methods don’t have a<em>timeout</em> parameter: use the <a class="reference internal" href="asyncio-task.html#asyncio.wait_for" title="asyncio.wait_for"><code class="xref py py-func docutils literal notranslate"><span class="pre">wait_for()</span></code></a> function;</p></li><li><p>the <a class="reference internal" href="#asyncio.subprocess.Process.wait" title="asyncio.subprocess.Process.wait"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Process.wait()</span></code></a> methodis asynchronous, whereas <a class="reference internal" href="subprocess.html#subprocess.Popen.wait" title="subprocess.Popen.wait"><code class="xref py py-meth docutils literal notranslate"><span class="pre">subprocess.Popen.wait()</span></code></a> methodis implemented as a blocking busy loop;</p></li><li><p>the <em>universal_newlines</em> parameter is not supported.</p></li></ul><p>This class is <a class="reference internal" href="asyncio-dev.html#asyncio-multithreading"><span class="std std-ref">not thread safe</span></a>.</p><p>See also the <a class="reference internal" href="#asyncio-subprocess-threads"><span class="std std-ref">Subprocess and Threads</span></a>section.</p><dl class="py method"><dt class="sig sig-object py" id="asyncio.subprocess.Process.wait"><em class="property"><span class="k"><span class="pre">async</span></span><span class="w"> </span></em><span class="sig-name descname"><span class="pre">wait</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.subprocess.Process.wait" title="Link to this definition">¶</a></dt><dd><p>Wait for the child process to terminate.</p><p>Set and return the <a class="reference internal" href="#asyncio.subprocess.Process.returncode" title="asyncio.subprocess.Process.returncode"><code class="xref py py-attr docutils literal notranslate"><span class="pre">returncode</span></code></a> attribute.</p><div class="admonition note"><p class="admonition-title">Note</p><p>This method can deadlock when using <code class="docutils literal notranslate"><span class="pre">stdout=PIPE</span></code> or<code class="docutils literal notranslate"><span class="pre">stderr=PIPE</span></code> and the child process generates so much outputthat it blocks waiting for the OS pipe buffer to acceptmore data. Use the <a class="reference internal" href="#asyncio.subprocess.Process.communicate" title="asyncio.subprocess.Process.communicate"><code class="xref py py-meth docutils literal notranslate"><span class="pre">communicate()</span></code></a> method when using pipesto avoid this condition.</p></div></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.subprocess.Process.communicate"><em class="property"><span class="k"><span class="pre">async</span></span><span class="w"> </span></em><span class="sig-name descname"><span class="pre">communicate</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">input</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.subprocess.Process.communicate" title="Link to this definition">¶</a></dt><dd><p>Interact with process:</p><ol class="arabic simple"><li><p>send data to <em>stdin</em> (if <em>input</em> is not <code class="docutils literal notranslate"><span class="pre">None</span></code>);</p></li><li><p>closes <em>stdin</em>;</p></li><li><p>read data from <em>stdout</em> and <em>stderr</em>, until EOF is reached;</p></li><li><p>wait for process to terminate.</p></li></ol><p>The optional <em>input</em> argument is the data (<a class="reference internal" href="stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> object)that will be sent to the child process.</p><p>Return a tuple <code class="docutils literal notranslate"><span class="pre">(stdout_data,</span> <span class="pre">stderr_data)</span></code>.</p><p>If either <a class="reference internal" href="exceptions.html#BrokenPipeError" title="BrokenPipeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">BrokenPipeError</span></code></a> or <a class="reference internal" href="exceptions.html#ConnectionResetError" title="ConnectionResetError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ConnectionResetError</span></code></a>exception is raised when writing <em>input</em> into <em>stdin</em>, theexception is ignored. This condition occurs when the processexits before all data are written into <em>stdin</em>.</p><p>If it is desired to send data to the process’ <em>stdin</em>,the process needs to be created with <code class="docutils literal notranslate"><span class="pre">stdin=PIPE</span></code>. Similarly,to get anything other than <code class="docutils literal notranslate"><span class="pre">None</span></code> in the result tuple, theprocess has to be created with <code class="docutils literal notranslate"><span class="pre">stdout=PIPE</span></code> and/or<code class="docutils literal notranslate"><span class="pre">stderr=PIPE</span></code> arguments.</p><p>Note, that the data read is buffered in memory, so do not usethis method if the data size is large or unlimited.</p><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.12: </span><em>stdin</em> gets closed when <code class="docutils literal notranslate"><span class="pre">input=None</span></code> too.</p></div></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.subprocess.Process.send_signal"><span class="sig-name descname"><span class="pre">send_signal</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">signal</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.subprocess.Process.send_signal" title="Link to this definition">¶</a></dt><dd><p>Sends the signal <em>signal</em> to the child process.</p><div class="admonition note"><p class="admonition-title">Note</p><p>On Windows, <a class="reference internal" href="signal.html#signal.SIGTERM" title="signal.SIGTERM"><code class="xref py py-const docutils literal notranslate"><span class="pre">SIGTERM</span></code></a> is an alias for <a class="reference internal" href="#asyncio.subprocess.Process.terminate" title="asyncio.subprocess.Process.terminate"><code class="xref py py-meth docutils literal notranslate"><span class="pre">terminate()</span></code></a>.<code class="docutils literal notranslate"><span class="pre">CTRL_C_EVENT</span></code> and <code class="docutils literal notranslate"><span class="pre">CTRL_BREAK_EVENT</span></code> can be sent to processesstarted with a <em>creationflags</em> parameter which includes<code class="docutils literal notranslate"><span class="pre">CREATE_NEW_PROCESS_GROUP</span></code>.</p></div></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.subprocess.Process.terminate"><span class="sig-name descname"><span class="pre">terminate</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.subprocess.Process.terminate" title="Link to this definition">¶</a></dt><dd><p>Stop the child process.</p><p>On POSIX systems this method sends <a class="reference internal" href="signal.html#signal.SIGTERM" title="signal.SIGTERM"><code class="xref py py-const docutils literal notranslate"><span class="pre">SIGTERM</span></code></a> to thechild process.</p><p>On Windows the Win32 API function <code class="xref c c-func docutils literal notranslate"><span class="pre">TerminateProcess()</span></code> iscalled to stop the child process.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.subprocess.Process.kill"><span class="sig-name descname"><span class="pre">kill</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.subprocess.Process.kill" title="Link to this definition">¶</a></dt><dd><p>Kill the child process.</p><p>On POSIX systems this method sends <a class="reference internal" href="signal.html#signal.SIGKILL" title="signal.SIGKILL"><code class="xref py py-data docutils literal notranslate"><span class="pre">SIGKILL</span></code></a> to the childprocess.</p><p>On Windows this method is an alias for <a class="reference internal" href="#asyncio.subprocess.Process.terminate" title="asyncio.subprocess.Process.terminate"><code class="xref py py-meth docutils literal notranslate"><span class="pre">terminate()</span></code></a>.</p></dd></dl>
<dl class="py attribute"><dt class="sig sig-object py" id="asyncio.subprocess.Process.stdin"><span class="sig-name descname"><span class="pre">stdin</span></span><a class="headerlink" href="#asyncio.subprocess.Process.stdin" title="Link to this definition">¶</a></dt><dd><p>Standard input stream (<a class="reference internal" href="asyncio-stream.html#asyncio.StreamWriter" title="asyncio.StreamWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamWriter</span></code></a>) or <code class="docutils literal notranslate"><span class="pre">None</span></code>if the process was created with <code class="docutils literal notranslate"><span class="pre">stdin=None</span></code>.</p></dd></dl>
<dl class="py attribute"><dt class="sig sig-object py" id="asyncio.subprocess.Process.stdout"><span class="sig-name descname"><span class="pre">stdout</span></span><a class="headerlink" href="#asyncio.subprocess.Process.stdout" title="Link to this definition">¶</a></dt><dd><p>Standard output stream (<a class="reference internal" href="asyncio-stream.html#asyncio.StreamReader" title="asyncio.StreamReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamReader</span></code></a>) or <code class="docutils literal notranslate"><span class="pre">None</span></code>if the process was created with <code class="docutils literal notranslate"><span class="pre">stdout=None</span></code>.</p></dd></dl>
<dl class="py attribute"><dt class="sig sig-object py" id="asyncio.subprocess.Process.stderr"><span class="sig-name descname"><span class="pre">stderr</span></span><a class="headerlink" href="#asyncio.subprocess.Process.stderr" title="Link to this definition">¶</a></dt><dd><p>Standard error stream (<a class="reference internal" href="asyncio-stream.html#asyncio.StreamReader" title="asyncio.StreamReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamReader</span></code></a>) or <code class="docutils literal notranslate"><span class="pre">None</span></code>if the process was created with <code class="docutils literal notranslate"><span class="pre">stderr=None</span></code>.</p></dd></dl>
<div class="admonition warning"><p class="admonition-title">Warning</p><p>Use the <a class="reference internal" href="#asyncio.subprocess.Process.communicate" title="asyncio.subprocess.Process.communicate"><code class="xref py py-meth docutils literal notranslate"><span class="pre">communicate()</span></code></a> method rather than<a class="reference internal" href="#asyncio.subprocess.Process.stdin" title="asyncio.subprocess.Process.stdin"><code class="xref py py-attr docutils literal notranslate"><span class="pre">process.stdin.write()</span></code></a>,<a class="reference internal" href="#asyncio.subprocess.Process.stdout" title="asyncio.subprocess.Process.stdout"><code class="xref py py-attr docutils literal notranslate"><span class="pre">await</span> <span class="pre">process.stdout.read()</span></code></a> or<a class="reference internal" href="#asyncio.subprocess.Process.stderr" title="asyncio.subprocess.Process.stderr"><code class="xref py py-attr docutils literal notranslate"><span class="pre">await</span> <span class="pre">process.stderr.read()</span></code></a>.This avoids deadlocks due to streams pausing reading or writingand blocking the child process.</p></div><dl class="py attribute"><dt class="sig sig-object py" id="asyncio.subprocess.Process.pid"><span class="sig-name descname"><span class="pre">pid</span></span><a class="headerlink" href="#asyncio.subprocess.Process.pid" title="Link to this definition">¶</a></dt><dd><p>Process identification number (PID).</p><p>Note that for processes created by the <a class="reference internal" href="#asyncio.create_subprocess_shell" title="asyncio.create_subprocess_shell"><code class="xref py py-func docutils literal notranslate"><span class="pre">create_subprocess_shell()</span></code></a>function, this attribute is the PID of the spawned shell.</p></dd></dl>
<dl class="py attribute"><dt class="sig sig-object py" id="asyncio.subprocess.Process.returncode"><span class="sig-name descname"><span class="pre">returncode</span></span><a class="headerlink" href="#asyncio.subprocess.Process.returncode" title="Link to this definition">¶</a></dt><dd><p>Return code of the process when it exits.</p><p>A <code class="docutils literal notranslate"><span class="pre">None</span></code> value indicates that the process has not terminated yet.</p><p>A negative value <code class="docutils literal notranslate"><span class="pre">-N</span></code> indicates that the child was terminatedby signal <code class="docutils literal notranslate"><span class="pre">N</span></code> (POSIX only).</p></dd></dl>
</dd></dl>
<section id="subprocess-and-threads"><span id="asyncio-subprocess-threads"></span><h3>Subprocess and Threads<a class="headerlink" href="#subprocess-and-threads" title="Link to this heading">¶</a></h3><p>Standard asyncio event loop supports running subprocesses from different threads bydefault.</p><p>On Windows subprocesses are provided by <a class="reference internal" href="asyncio-eventloop.html#asyncio.ProactorEventLoop" title="asyncio.ProactorEventLoop"><code class="xref py py-class docutils literal notranslate"><span class="pre">ProactorEventLoop</span></code></a> only (default),<a class="reference internal" href="asyncio-eventloop.html#asyncio.SelectorEventLoop" title="asyncio.SelectorEventLoop"><code class="xref py py-class docutils literal notranslate"><span class="pre">SelectorEventLoop</span></code></a> has no subprocess support.</p><p>Note that alternative event loop implementations might have own limitations;please refer to their documentation.</p><div class="admonition seealso"><p class="admonition-title">See also</p><p>The <a class="reference internal" href="asyncio-dev.html#asyncio-multithreading"><span class="std std-ref">Concurrency and multithreading in asyncio</span></a> section.</p></div></section><section id="examples"><h3>Examples<a class="headerlink" href="#examples" title="Link to this heading">¶</a></h3><p>An example using the <a class="reference internal" href="#asyncio.subprocess.Process" title="asyncio.subprocess.Process"><code class="xref py py-class docutils literal notranslate"><span class="pre">Process</span></code></a> class tocontrol a subprocess and the <a class="reference internal" href="asyncio-stream.html#asyncio.StreamReader" title="asyncio.StreamReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamReader</span></code></a> class to read fromits standard output.</p><p id="asyncio-example-create-subprocess-exec">The subprocess is created by the <a class="reference internal" href="#asyncio.create_subprocess_exec" title="asyncio.create_subprocess_exec"><code class="xref py py-func docutils literal notranslate"><span class="pre">create_subprocess_exec()</span></code></a>function:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span><span class="w"> </span><span class="nn">asyncio</span><span class="kn">import</span><span class="w"> </span><span class="nn">sys</span>
<span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">get_date</span><span class="p">():</span> <span class="n">code</span> <span class="o">=</span> <span class="s1">'import datetime; print(datetime.datetime.now())'</span>
<span class="c1"># Create the subprocess; redirect the standard output</span> <span class="c1"># into a pipe.</span> <span class="n">proc</span> <span class="o">=</span> <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">create_subprocess_exec</span><span class="p">(</span> <span class="n">sys</span><span class="o">.</span><span class="n">executable</span><span class="p">,</span> <span class="s1">'-c'</span><span class="p">,</span> <span class="n">code</span><span class="p">,</span> <span class="n">stdout</span><span class="o">=</span><span class="n">asyncio</span><span class="o">.</span><span class="n">subprocess</span><span class="o">.</span><span class="n">PIPE</span><span class="p">)</span>
<span class="c1"># Read one line of output.</span> <span class="n">data</span> <span class="o">=</span> <span class="k">await</span> <span class="n">proc</span><span class="o">.</span><span class="n">stdout</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span> <span class="n">line</span> <span class="o">=</span> <span class="n">data</span><span class="o">.</span><span class="n">decode</span><span class="p">(</span><span class="s1">'ascii'</span><span class="p">)</span><span class="o">.</span><span class="n">rstrip</span><span class="p">()</span>
<span class="c1"># Wait for the subprocess exit.</span> <span class="k">await</span> <span class="n">proc</span><span class="o">.</span><span class="n">wait</span><span class="p">()</span> <span class="k">return</span> <span class="n">line</span>
<span class="n">date</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="n">get_date</span><span class="p">())</span><span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">"Current date: </span><span class="si">{</span><span class="n">date</span><span class="si">}</span><span class="s2">"</span><span class="p">)</span></pre></div></div><p>See also the <a class="reference internal" href="asyncio-protocol.html#asyncio-example-subprocess-proto"><span class="std std-ref">same example</span></a>written using low-level APIs.</p></section></section></section>
<div class="clearer"></div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="Main"> <div class="sphinxsidebarwrapper"> <div> <h3><a href="../contents.html">Table of Contents</a></h3> <ul><li><a class="reference internal" href="#">Subprocesses</a><ul><li><a class="reference internal" href="#creating-subprocesses">Creating Subprocesses</a></li><li><a class="reference internal" href="#constants">Constants</a></li><li><a class="reference internal" href="#interacting-with-subprocesses">Interacting with Subprocesses</a><ul><li><a class="reference internal" href="#subprocess-and-threads">Subprocess and Threads</a></li><li><a class="reference internal" href="#examples">Examples</a></li></ul></li></ul></li></ul>
</div> <div> <h4>Previous topic</h4> <p class="topless"><a href="asyncio-sync.html" title="previous chapter">Synchronization Primitives</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="asyncio-queue.html" title="next chapter">Queues</a></p> </div> <script> document.addEventListener('DOMContentLoaded', () => { const title = document.querySelector('meta[property="og:title"]').content; const elements = document.querySelectorAll('.improvepage'); const pageurl = window.location.href.split('?')[0]; elements.forEach(element => { const url = new URL(element.href.split('?')[0].replace("-nojs", "")); url.searchParams.set('pagetitle', title); url.searchParams.set('pageurl', pageurl); url.searchParams.set('pagesource', "library/asyncio-subprocess.rst"); element.href = url.toString(); }); }); </script> <div role="note" aria-label="source link"> <h3>This page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a bug</a></li> <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li> <li> <a href="https://github.com/python/cpython/blob/main/Doc/library/asyncio-subprocess.rst?plain=1" rel="nofollow">Show source </a> </li> </ul> </div> </div><div id="sidebarbutton" title="Collapse sidebar"><span>«</span></div>
</div> <div class="clearer"></div> </div> <div class="related" role="navigation" aria-label="Related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="asyncio-queue.html" title="Queues" >next</a> |</li> <li class="right" > <a href="asyncio-sync.html" title="Synchronization Primitives" >previous</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.15.0a6 Documentation</a> » </li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="ipc.html" >Networking and Interprocess Communication</a> »</li> <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> »</li> <li class="nav-item nav-item-this"><a href="">Subprocesses</a></li> <li class="right">
<div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box"> <input type="submit" value="Go"> </form> </div> | </li> <li class="right"><label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> |</li> </ul> </div> <div class="footer"> © <a href="../copyright.html">Copyright</a> 2001 Python Software Foundation. <br> This page is licensed under the Python Software Foundation License Version 2. <br> Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. <br> See <a href="/license.html">History and License</a> for more information.<br> <br>
The Python Software Foundation is a non-profit corporation.<a href="https://www.python.org/psf/donations/">Please donate.</a><br> <br> Last updated on Mar 10, 2026 (08:58 UTC). <a href="/bugs.html">Found a bug</a>? <br>
Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3. </div>
</body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844<!DOCTYPE html>
<html lang="en" data-content_root="../"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta property="og:title" content="Synchronization Primitives" /><meta property="og:type" content="website" /><meta property="og:url" content="https://docs.python.org/3/library/asyncio-sync.html" /><meta property="og:site_name" content="Python documentation" /><meta property="og:description" content="Source code: Lib/asyncio/locks.py asyncio synchronization primitives are designed to be similar to those of the threading module with two important caveats: asyncio primitives are not thread-safe, ..." /><meta property="og:image:width" content="1146" /><meta property="og:image:height" content="600" /><meta property="og:image" content="https://docs.python.org/3.15/_images/social_previews/summary_library_asyncio-sync_155db036.png" /><meta property="og:image:alt" content="Source code: Lib/asyncio/locks.py asyncio synchronization primitives are designed to be similar to those of the threading module with two important caveats: asyncio primitives are not thread-safe, ..." /><meta name="description" content="Source code: Lib/asyncio/locks.py asyncio synchronization primitives are designed to be similar to those of the threading module with two important caveats: asyncio primitives are not thread-safe, ..." /><meta name="twitter:card" content="summary_large_image" /><meta name="theme-color" content="#3776ab">
<title>Synchronization Primitives — Python 3.15.0a6 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" /> <link rel="stylesheet" type="text/css" href="../_static/classic.css?v=234b1a7c" /> <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=89a2f22a" /> <link rel="stylesheet" type="text/css" href="../_static/profiling-sampling-visualization.css?v=0c2600ae" /> <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" /> <script src="../_static/documentation_options.js?v=6b7c9ff5"></script> <script src="../_static/doctools.js?v=9bcbadda"></script> <script src="../_static/sphinx_highlight.js?v=dc90522c"></script> <script src="../_static/profiling-sampling-visualization.js?v=9811ed04"></script> <script src="../_static/sidebar.js"></script> <link rel="search" type="application/opensearchdescription+xml" title="Search within Python 3.15.0a6 documentation" href="../_static/opensearch.xml"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="copyright" title="Copyright" href="../copyright.html" /> <link rel="next" title="Subprocesses" href="asyncio-subprocess.html" /> <link rel="prev" title="Streams" href="asyncio-stream.html" /> <script defer file-types="bz2,epub,zip" data-domain="docs.python.org" src="https://analytics.python.org/js/script.file-downloads.outbound-links.js"></script> <link rel="canonical" href="https://docs.python.org/3/library/asyncio-sync.html">
<style> @media only screen { table.full-width-table { width: 100%; } } </style><link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css"> <link rel="shortcut icon" type="image/png" href="../_static/py.svg"> <script type="text/javascript" src="../_static/copybutton.js"></script> <script type="text/javascript" src="../_static/menu.js"></script> <script type="text/javascript" src="../_static/search-focus.js"></script> <script type="text/javascript" src="../_static/themetoggle.js"></script> <script type="text/javascript" src="../_static/rtd_switcher.js"></script> <meta name="readthedocs-addons-api-version" content="1">
</head><body><div class="mobile-nav"> <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation" aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu"> <nav class="nav-content" role="navigation"> <label for="menuToggler" class="toggler__label"> <span></span> </label> <span class="nav-items-wrapper"> <a href="https://www.python.org/" class="nav-logo"> <img src="../_static/py.svg" alt="Python logo"> </a> <span class="version_switcher_placeholder"></span> <form role="search" class="search" action="../search.html" method="get"> <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon"> <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> </svg> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q"> <input type="submit" value="Go"> </form> </span> </nav> <div class="menu-wrapper"> <nav class="menu" role="navigation" aria-label="main navigation"> <div class="language_switcher_placeholder"></div> <label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> <div> <h3><a href="../contents.html">Table of Contents</a></h3> <ul><li><a class="reference internal" href="#">Synchronization Primitives</a><ul><li><a class="reference internal" href="#lock">Lock</a></li><li><a class="reference internal" href="#event">Event</a></li><li><a class="reference internal" href="#condition">Condition</a></li><li><a class="reference internal" href="#semaphore">Semaphore</a></li><li><a class="reference internal" href="#boundedsemaphore">BoundedSemaphore</a></li><li><a class="reference internal" href="#barrier">Barrier</a></li></ul></li></ul>
</div> <div> <h4>Previous topic</h4> <p class="topless"><a href="asyncio-stream.html" title="previous chapter">Streams</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="asyncio-subprocess.html" title="next chapter">Subprocesses</a></p> </div> <script> document.addEventListener('DOMContentLoaded', () => { const title = document.querySelector('meta[property="og:title"]').content; const elements = document.querySelectorAll('.improvepage'); const pageurl = window.location.href.split('?')[0]; elements.forEach(element => { const url = new URL(element.href.split('?')[0].replace("-nojs", "")); url.searchParams.set('pagetitle', title); url.searchParams.set('pageurl', pageurl); url.searchParams.set('pagesource', "library/asyncio-sync.rst"); element.href = url.toString(); }); }); </script> <div role="note" aria-label="source link"> <h3>This page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a bug</a></li> <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li> <li> <a href="https://github.com/python/cpython/blob/main/Doc/library/asyncio-sync.rst?plain=1" rel="nofollow">Show source </a> </li> </ul> </div> </nav> </div></div>
<div class="related" role="navigation" aria-label="Related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="asyncio-subprocess.html" title="Subprocesses" accesskey="N">next</a> |</li> <li class="right" > <a href="asyncio-stream.html" title="Streams" accesskey="P">previous</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.15.0a6 Documentation</a> » </li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="ipc.html" >Networking and Interprocess Communication</a> »</li> <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> »</li> <li class="nav-item nav-item-this"><a href="">Synchronization Primitives</a></li> <li class="right">
<div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box"> <input type="submit" value="Go"> </form> </div> | </li> <li class="right"><label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> |</li> </ul> </div>
<div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <section id="synchronization-primitives"><span id="asyncio-sync"></span><h1>Synchronization Primitives<a class="headerlink" href="#synchronization-primitives" title="Link to this heading">¶</a></h1><p><strong>Source code:</strong> <a class="extlink-source reference external" href="https://github.com/python/cpython/tree/main/Lib/asyncio/locks.py">Lib/asyncio/locks.py</a></p><hr class="docutils" /><p>asyncio synchronization primitives are designed to be similar tothose of the <a class="reference internal" href="threading.html#module-threading" title="threading: Thread-based parallelism."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a> module with two important caveats:</p><ul class="simple"><li><p>asyncio primitives are not thread-safe, therefore they should notbe used for OS thread synchronization (use <a class="reference internal" href="threading.html#module-threading" title="threading: Thread-based parallelism."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a> forthat);</p></li><li><p>methods of these synchronization primitives do not accept the <em>timeout</em>argument; use the <a class="reference internal" href="asyncio-task.html#asyncio.wait_for" title="asyncio.wait_for"><code class="xref py py-func docutils literal notranslate"><span class="pre">asyncio.wait_for()</span></code></a> function to performoperations with timeouts.</p></li></ul><p>asyncio has the following basic synchronization primitives:</p><ul class="simple"><li><p><a class="reference internal" href="#asyncio.Lock" title="asyncio.Lock"><code class="xref py py-class docutils literal notranslate"><span class="pre">Lock</span></code></a></p></li><li><p><a class="reference internal" href="#asyncio.Event" title="asyncio.Event"><code class="xref py py-class docutils literal notranslate"><span class="pre">Event</span></code></a></p></li><li><p><a class="reference internal" href="#asyncio.Condition" title="asyncio.Condition"><code class="xref py py-class docutils literal notranslate"><span class="pre">Condition</span></code></a></p></li><li><p><a class="reference internal" href="#asyncio.Semaphore" title="asyncio.Semaphore"><code class="xref py py-class docutils literal notranslate"><span class="pre">Semaphore</span></code></a></p></li><li><p><a class="reference internal" href="#asyncio.BoundedSemaphore" title="asyncio.BoundedSemaphore"><code class="xref py py-class docutils literal notranslate"><span class="pre">BoundedSemaphore</span></code></a></p></li><li><p><a class="reference internal" href="#asyncio.Barrier" title="asyncio.Barrier"><code class="xref py py-class docutils literal notranslate"><span class="pre">Barrier</span></code></a></p></li></ul><hr class="docutils" /><section id="lock"><h2>Lock<a class="headerlink" href="#lock" title="Link to this heading">¶</a></h2><dl class="py class"><dt class="sig sig-object py" id="asyncio.Lock"><em class="property"><span class="k"><span class="pre">class</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">Lock</span></span><a class="headerlink" href="#asyncio.Lock" title="Link to this definition">¶</a></dt><dd><p>Implements a mutex lock for asyncio tasks. Not thread-safe.</p><p>An asyncio lock can be used to guarantee exclusive access to ashared resource.</p><p>The preferred way to use a Lock is an <a class="reference internal" href="../reference/compound_stmts.html#async-with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">with</span></code></a>statement:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">lock</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">Lock</span><span class="p">()</span>
<span class="c1"># ... later</span><span class="k">async</span> <span class="k">with</span> <span class="n">lock</span><span class="p">:</span> <span class="c1"># access shared state</span></pre></div></div><p>which is equivalent to:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">lock</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">Lock</span><span class="p">()</span>
<span class="c1"># ... later</span><span class="k">await</span> <span class="n">lock</span><span class="o">.</span><span class="n">acquire</span><span class="p">()</span><span class="k">try</span><span class="p">:</span> <span class="c1"># access shared state</span><span class="k">finally</span><span class="p">:</span> <span class="n">lock</span><span class="o">.</span><span class="n">release</span><span class="p">()</span></pre></div></div><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.10: </span>Removed the <em>loop</em> parameter.</p></div><dl class="py method"><dt class="sig sig-object py" id="asyncio.Lock.acquire"><em class="property"><span class="k"><span class="pre">async</span></span><span class="w"> </span></em><span class="sig-name descname"><span class="pre">acquire</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Lock.acquire" title="Link to this definition">¶</a></dt><dd><p>Acquire the lock.</p><p>This method waits until the lock is <em>unlocked</em>, sets it to<em>locked</em> and returns <code class="docutils literal notranslate"><span class="pre">True</span></code>.</p><p>When more than one coroutine is blocked in <code class="xref py py-meth docutils literal notranslate"><span class="pre">acquire()</span></code>waiting for the lock to be unlocked, only one coroutineeventually proceeds.</p><p>Acquiring a lock is <em>fair</em>: the coroutine that proceeds will bethe first coroutine that started waiting on the lock.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.Lock.release"><span class="sig-name descname"><span class="pre">release</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Lock.release" title="Link to this definition">¶</a></dt><dd><p>Release the lock.</p><p>When the lock is <em>locked</em>, reset it to <em>unlocked</em> and return.</p><p>If the lock is <em>unlocked</em>, a <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.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.Lock.locked"><span class="sig-name descname"><span class="pre">locked</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Lock.locked" title="Link to this definition">¶</a></dt><dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the lock is <em>locked</em>.</p></dd></dl>
</dd></dl>
</section><section id="event"><h2>Event<a class="headerlink" href="#event" title="Link to this heading">¶</a></h2><dl class="py class"><dt class="sig sig-object py" id="asyncio.Event"><em class="property"><span class="k"><span class="pre">class</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">Event</span></span><a class="headerlink" href="#asyncio.Event" title="Link to this definition">¶</a></dt><dd><p>An event object. Not thread-safe.</p><p>An asyncio event can be used to notify multiple asyncio tasksthat some event has happened.</p><p>An Event object manages an internal flag that can be set to <em>true</em>with the <a class="reference internal" href="#asyncio.Event.set" title="asyncio.Event.set"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set()</span></code></a> method and reset to <em>false</em> with the<a class="reference internal" href="#asyncio.Event.clear" title="asyncio.Event.clear"><code class="xref py py-meth docutils literal notranslate"><span class="pre">clear()</span></code></a> method. The <a class="reference internal" href="#asyncio.Event.wait" title="asyncio.Event.wait"><code class="xref py py-meth docutils literal notranslate"><span class="pre">wait()</span></code></a> method blocks until theflag is set to <em>true</em>. The flag is set to <em>false</em> initially.</p><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.10: </span>Removed the <em>loop</em> parameter.</p></div><p id="asyncio-example-sync-event">Example:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">waiter</span><span class="p">(</span><span class="n">event</span><span class="p">):</span> <span class="nb">print</span><span class="p">(</span><span class="s1">'waiting for it ...'</span><span class="p">)</span> <span class="k">await</span> <span class="n">event</span><span class="o">.</span><span class="n">wait</span><span class="p">()</span> <span class="nb">print</span><span class="p">(</span><span class="s1">'... got it!'</span><span class="p">)</span>
<span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">main</span><span class="p">():</span> <span class="c1"># Create an Event object.</span> <span class="n">event</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">Event</span><span class="p">()</span>
<span class="c1"># Spawn a Task to wait until 'event' is set.</span> <span class="n">waiter_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">waiter</span><span class="p">(</span><span class="n">event</span><span class="p">))</span>
<span class="c1"># Sleep for 1 second and set the event.</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> <span class="n">event</span><span class="o">.</span><span class="n">set</span><span class="p">()</span>
<span class="c1"># Wait until the waiter task is finished.</span> <span class="k">await</span> <span class="n">waiter_task</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></pre></div></div><dl class="py method"><dt class="sig sig-object py" id="asyncio.Event.wait"><em class="property"><span class="k"><span class="pre">async</span></span><span class="w"> </span></em><span class="sig-name descname"><span class="pre">wait</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Event.wait" title="Link to this definition">¶</a></dt><dd><p>Wait until the event is set.</p><p>If the event is set, return <code class="docutils literal notranslate"><span class="pre">True</span></code> immediately.Otherwise block until another task calls <a class="reference internal" href="#asyncio.Event.set" title="asyncio.Event.set"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set()</span></code></a>.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.Event.set"><span class="sig-name descname"><span class="pre">set</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Event.set" title="Link to this definition">¶</a></dt><dd><p>Set the event.</p><p>All tasks waiting for event to be set will be immediatelyawakened.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.Event.clear"><span class="sig-name descname"><span class="pre">clear</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Event.clear" title="Link to this definition">¶</a></dt><dd><p>Clear (unset) the event.</p><p>Subsequent tasks awaiting on <a class="reference internal" href="#asyncio.Event.wait" title="asyncio.Event.wait"><code class="xref py py-meth docutils literal notranslate"><span class="pre">wait()</span></code></a> will now block until the<a class="reference internal" href="#asyncio.Event.set" title="asyncio.Event.set"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set()</span></code></a> method is called again.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.Event.is_set"><span class="sig-name descname"><span class="pre">is_set</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Event.is_set" title="Link to this definition">¶</a></dt><dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the event is set.</p></dd></dl>
</dd></dl>
</section><section id="condition"><h2>Condition<a class="headerlink" href="#condition" title="Link to this heading">¶</a></h2><dl class="py class"><dt class="sig sig-object py" id="asyncio.Condition"><em class="property"><span class="k"><span class="pre">class</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">Condition</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">lock</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.Condition" title="Link to this definition">¶</a></dt><dd><p>A Condition object. Not thread-safe.</p><p>An asyncio condition primitive can be used by a task to wait forsome event to happen and then get exclusive access to a sharedresource.</p><p>In essence, a Condition object combines the functionalityof an <a class="reference internal" href="#asyncio.Event" title="asyncio.Event"><code class="xref py py-class docutils literal notranslate"><span class="pre">Event</span></code></a> and a <a class="reference internal" href="#asyncio.Lock" title="asyncio.Lock"><code class="xref py py-class docutils literal notranslate"><span class="pre">Lock</span></code></a>. It is possible to havemultiple Condition objects share one Lock, which allows coordinatingexclusive access to a shared resource between different tasksinterested in particular states of that shared resource.</p><p>The optional <em>lock</em> argument must be a <a class="reference internal" href="#asyncio.Lock" title="asyncio.Lock"><code class="xref py py-class docutils literal notranslate"><span class="pre">Lock</span></code></a> object or<code class="docutils literal notranslate"><span class="pre">None</span></code>. In the latter case a new Lock object is createdautomatically.</p><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.10: </span>Removed the <em>loop</em> parameter.</p></div><p>The preferred way to use a Condition is an <a class="reference internal" href="../reference/compound_stmts.html#async-with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">with</span></code></a>statement:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">cond</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">Condition</span><span class="p">()</span>
<span class="c1"># ... later</span><span class="k">async</span> <span class="k">with</span> <span class="n">cond</span><span class="p">:</span> <span class="k">await</span> <span class="n">cond</span><span class="o">.</span><span class="n">wait</span><span class="p">()</span></pre></div></div><p>which is equivalent to:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">cond</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">Condition</span><span class="p">()</span>
<span class="c1"># ... later</span><span class="k">await</span> <span class="n">cond</span><span class="o">.</span><span class="n">acquire</span><span class="p">()</span><span class="k">try</span><span class="p">:</span> <span class="k">await</span> <span class="n">cond</span><span class="o">.</span><span class="n">wait</span><span class="p">()</span><span class="k">finally</span><span class="p">:</span> <span class="n">cond</span><span class="o">.</span><span class="n">release</span><span class="p">()</span></pre></div></div><dl class="py method"><dt class="sig sig-object py" id="asyncio.Condition.acquire"><em class="property"><span class="k"><span class="pre">async</span></span><span class="w"> </span></em><span class="sig-name descname"><span class="pre">acquire</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Condition.acquire" title="Link to this definition">¶</a></dt><dd><p>Acquire the underlying lock.</p><p>This method waits until the underlying lock is <em>unlocked</em>,sets it to <em>locked</em> and returns <code class="docutils literal notranslate"><span class="pre">True</span></code>.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.Condition.notify"><span class="sig-name descname"><span class="pre">notify</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">n</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">1</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Condition.notify" title="Link to this definition">¶</a></dt><dd><p>Wake up <em>n</em> tasks (1 by default) waiting on thiscondition. If fewer than <em>n</em> tasks are waiting they are all awakened.</p><p>The lock must be acquired before this method is called andreleased shortly after. If called with an <em>unlocked</em> locka <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> error is raised.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.Condition.locked"><span class="sig-name descname"><span class="pre">locked</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Condition.locked" title="Link to this definition">¶</a></dt><dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the underlying lock is acquired.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.Condition.notify_all"><span class="sig-name descname"><span class="pre">notify_all</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Condition.notify_all" title="Link to this definition">¶</a></dt><dd><p>Wake up all tasks waiting on this condition.</p><p>This method acts like <a class="reference internal" href="#asyncio.Condition.notify" title="asyncio.Condition.notify"><code class="xref py py-meth docutils literal notranslate"><span class="pre">notify()</span></code></a>, but wakes up all waitingtasks.</p><p>The lock must be acquired before this method is called andreleased shortly after. If called with an <em>unlocked</em> locka <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> error is raised.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.Condition.release"><span class="sig-name descname"><span class="pre">release</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Condition.release" title="Link to this definition">¶</a></dt><dd><p>Release the underlying lock.</p><p>When invoked on an unlocked lock, a <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> israised.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.Condition.wait"><em class="property"><span class="k"><span class="pre">async</span></span><span class="w"> </span></em><span class="sig-name descname"><span class="pre">wait</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Condition.wait" title="Link to this definition">¶</a></dt><dd><p>Wait until notified.</p><p>If the calling task has not acquired the lock when this method iscalled, a <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.</p><p>This method releases the underlying lock, and then blocks untilit is awakened by a <a class="reference internal" href="#asyncio.Condition.notify" title="asyncio.Condition.notify"><code class="xref py py-meth docutils literal notranslate"><span class="pre">notify()</span></code></a> or <a class="reference internal" href="#asyncio.Condition.notify_all" title="asyncio.Condition.notify_all"><code class="xref py py-meth docutils literal notranslate"><span class="pre">notify_all()</span></code></a> call.Once awakened, the Condition re-acquires its lock and this methodreturns <code class="docutils literal notranslate"><span class="pre">True</span></code>.</p><p>Note that a task <em>may</em> return from this call spuriously,which is why the caller should always re-check the stateand be prepared to <code class="xref py py-meth docutils literal notranslate"><span class="pre">wait()</span></code> again. For this reason, you mayprefer to use <a class="reference internal" href="#asyncio.Condition.wait_for" title="asyncio.Condition.wait_for"><code class="xref py py-meth docutils literal notranslate"><span class="pre">wait_for()</span></code></a> instead.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.Condition.wait_for"><em class="property"><span class="k"><span class="pre">async</span></span><span class="w"> </span></em><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">predicate</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Condition.wait_for" title="Link to this definition">¶</a></dt><dd><p>Wait until a predicate becomes <em>true</em>.</p><p>The predicate must be a callable which result will beinterpreted as a boolean value. The method will repeatedly<a class="reference internal" href="#asyncio.Condition.wait" title="asyncio.Condition.wait"><code class="xref py py-meth docutils literal notranslate"><span class="pre">wait()</span></code></a> until the predicate evaluates to <em>true</em>. The final value is thereturn value.</p></dd></dl>
</dd></dl>
</section><section id="semaphore"><h2>Semaphore<a class="headerlink" href="#semaphore" title="Link to this heading">¶</a></h2><dl class="py class"><dt class="sig sig-object py" id="asyncio.Semaphore"><em class="property"><span class="k"><span class="pre">class</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">Semaphore</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">value</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">1</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Semaphore" title="Link to this definition">¶</a></dt><dd><p>A Semaphore object. Not thread-safe.</p><p>A semaphore manages an internal counter which is decremented by each<a class="reference internal" href="#asyncio.Semaphore.acquire" title="asyncio.Semaphore.acquire"><code class="xref py py-meth docutils literal notranslate"><span class="pre">acquire()</span></code></a> call and incremented by each <a class="reference internal" href="#asyncio.Semaphore.release" title="asyncio.Semaphore.release"><code class="xref py py-meth docutils literal notranslate"><span class="pre">release()</span></code></a> call.The counter can never go below zero; when <code class="xref py py-meth docutils literal notranslate"><span class="pre">acquire()</span></code> findsthat it is zero, it blocks, waiting until some task calls<code class="xref py py-meth docutils literal notranslate"><span class="pre">release()</span></code>.</p><p>The optional <em>value</em> argument gives the initial value for theinternal counter (<code class="docutils literal notranslate"><span class="pre">1</span></code> by default). If the given value isless than <code class="docutils literal notranslate"><span class="pre">0</span></code> a <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> is raised.</p><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.10: </span>Removed the <em>loop</em> parameter.</p></div><p>The preferred way to use a Semaphore is an <a class="reference internal" href="../reference/compound_stmts.html#async-with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">with</span></code></a>statement:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">sem</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">Semaphore</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span>
<span class="c1"># ... later</span><span class="k">async</span> <span class="k">with</span> <span class="n">sem</span><span class="p">:</span> <span class="c1"># work with shared resource</span></pre></div></div><p>which is equivalent to:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">sem</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">Semaphore</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span>
<span class="c1"># ... later</span><span class="k">await</span> <span class="n">sem</span><span class="o">.</span><span class="n">acquire</span><span class="p">()</span><span class="k">try</span><span class="p">:</span> <span class="c1"># work with shared resource</span><span class="k">finally</span><span class="p">:</span> <span class="n">sem</span><span class="o">.</span><span class="n">release</span><span class="p">()</span></pre></div></div><dl class="py method"><dt class="sig sig-object py" id="asyncio.Semaphore.acquire"><em class="property"><span class="k"><span class="pre">async</span></span><span class="w"> </span></em><span class="sig-name descname"><span class="pre">acquire</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Semaphore.acquire" title="Link to this definition">¶</a></dt><dd><p>Acquire a semaphore.</p><p>If the internal counter is greater than zero, decrementit by one and return <code class="docutils literal notranslate"><span class="pre">True</span></code> immediately. If it is zero, waituntil a <a class="reference internal" href="#asyncio.Semaphore.release" title="asyncio.Semaphore.release"><code class="xref py py-meth docutils literal notranslate"><span class="pre">release()</span></code></a> is called and return <code class="docutils literal notranslate"><span class="pre">True</span></code>.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.Semaphore.locked"><span class="sig-name descname"><span class="pre">locked</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Semaphore.locked" title="Link to this definition">¶</a></dt><dd><p>Returns <code class="docutils literal notranslate"><span class="pre">True</span></code> if semaphore can not be acquired immediately.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.Semaphore.release"><span class="sig-name descname"><span class="pre">release</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Semaphore.release" title="Link to this definition">¶</a></dt><dd><p>Release a semaphore, incrementing the internal counter by one.Can wake up a task waiting to acquire the semaphore.</p><p>Unlike <a class="reference internal" href="#asyncio.BoundedSemaphore" title="asyncio.BoundedSemaphore"><code class="xref py py-class docutils literal notranslate"><span class="pre">BoundedSemaphore</span></code></a>, <code class="xref py py-class docutils literal notranslate"><span class="pre">Semaphore</span></code> allowsmaking more <code class="docutils literal notranslate"><span class="pre">release()</span></code> calls than <code class="docutils literal notranslate"><span class="pre">acquire()</span></code> calls.</p></dd></dl>
</dd></dl>
</section><section id="boundedsemaphore"><h2>BoundedSemaphore<a class="headerlink" href="#boundedsemaphore" title="Link to this heading">¶</a></h2><dl class="py class"><dt class="sig sig-object py" id="asyncio.BoundedSemaphore"><em class="property"><span class="k"><span class="pre">class</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">BoundedSemaphore</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">value</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">1</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.BoundedSemaphore" title="Link to this definition">¶</a></dt><dd><p>A bounded semaphore object. Not thread-safe.</p><p>Bounded Semaphore is a version of <a class="reference internal" href="#asyncio.Semaphore" title="asyncio.Semaphore"><code class="xref py py-class docutils literal notranslate"><span class="pre">Semaphore</span></code></a> that raisesa <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> in <a class="reference internal" href="#asyncio.Semaphore.release" title="asyncio.Semaphore.release"><code class="xref py py-meth docutils literal notranslate"><span class="pre">release()</span></code></a> if itincreases the internal counter above the initial <em>value</em>.</p><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.10: </span>Removed the <em>loop</em> parameter.</p></div></dd></dl>
</section><section id="barrier"><h2>Barrier<a class="headerlink" href="#barrier" title="Link to this heading">¶</a></h2><dl class="py class"><dt class="sig sig-object py" id="asyncio.Barrier"><em class="property"><span class="k"><span class="pre">class</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">Barrier</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">parties</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Barrier" title="Link to this definition">¶</a></dt><dd><p>A barrier object. Not thread-safe.</p><p>A barrier is a simple synchronization primitive that allows to block until<em>parties</em> number of tasks are waiting on it.Tasks can wait on the <a class="reference internal" href="#asyncio.Barrier.wait" title="asyncio.Barrier.wait"><code class="xref py py-meth docutils literal notranslate"><span class="pre">wait()</span></code></a> method and would be blocked untilthe specified number of tasks end up waiting on <code class="xref py py-meth docutils literal notranslate"><span class="pre">wait()</span></code>.At that point all of the waiting tasks would unblock simultaneously.</p><p><a class="reference internal" href="../reference/compound_stmts.html#async-with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">with</span></code></a> can be used as an alternative to awaiting on<a class="reference internal" href="#asyncio.Barrier.wait" title="asyncio.Barrier.wait"><code class="xref py py-meth docutils literal notranslate"><span class="pre">wait()</span></code></a>.</p><p>The barrier can be reused any number of times.</p><p id="asyncio-example-barrier">Example:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">example_barrier</span><span class="p">():</span> <span class="c1"># barrier with 3 parties</span> <span class="n">b</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">Barrier</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>
<span class="c1"># create 2 new waiting tasks</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">create_task</span><span class="p">(</span><span class="n">b</span><span class="o">.</span><span class="n">wait</span><span class="p">())</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">create_task</span><span class="p">(</span><span class="n">b</span><span class="o">.</span><span class="n">wait</span><span class="p">())</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">0</span><span class="p">)</span> <span class="nb">print</span><span class="p">(</span><span class="n">b</span><span class="p">)</span>
<span class="c1"># The third .wait() call passes the barrier</span> <span class="k">await</span> <span class="n">b</span><span class="o">.</span><span class="n">wait</span><span class="p">()</span> <span class="nb">print</span><span class="p">(</span><span class="n">b</span><span class="p">)</span> <span class="nb">print</span><span class="p">(</span><span class="s2">"barrier passed"</span><span class="p">)</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">0</span><span class="p">)</span> <span class="nb">print</span><span class="p">(</span><span class="n">b</span><span class="p">)</span>
<span class="n">asyncio</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="n">example_barrier</span><span class="p">())</span></pre></div></div><p>Result of this example is:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="o"><</span><span class="n">asyncio</span><span class="o">.</span><span class="n">locks</span><span class="o">.</span><span class="n">Barrier</span> <span class="nb">object</span> <span class="n">at</span> <span class="mi">0</span><span class="n">x</span><span class="o">...</span> <span class="p">[</span><span class="n">filling</span><span class="p">,</span> <span class="n">waiters</span><span class="p">:</span><span class="mi">2</span><span class="o">/</span><span class="mi">3</span><span class="p">]</span><span class="o">></span><span class="o"><</span><span class="n">asyncio</span><span class="o">.</span><span class="n">locks</span><span class="o">.</span><span class="n">Barrier</span> <span class="nb">object</span> <span class="n">at</span> <span class="mi">0</span><span class="n">x</span><span class="o">...</span> <span class="p">[</span><span class="n">draining</span><span class="p">,</span> <span class="n">waiters</span><span class="p">:</span><span class="mi">0</span><span class="o">/</span><span class="mi">3</span><span class="p">]</span><span class="o">></span><span class="n">barrier</span> <span class="n">passed</span><span class="o"><</span><span class="n">asyncio</span><span class="o">.</span><span class="n">locks</span><span class="o">.</span><span class="n">Barrier</span> <span class="nb">object</span> <span class="n">at</span> <span class="mi">0</span><span class="n">x</span><span class="o">...</span> <span class="p">[</span><span class="n">filling</span><span class="p">,</span> <span class="n">waiters</span><span class="p">:</span><span class="mi">0</span><span class="o">/</span><span class="mi">3</span><span class="p">]</span><span class="o">></span></pre></div></div><div class="versionadded"><p><span class="versionmodified added">Added in version 3.11.</span></p></div><dl class="py method"><dt class="sig sig-object py" id="asyncio.Barrier.wait"><em class="property"><span class="k"><span class="pre">async</span></span><span class="w"> </span></em><span class="sig-name descname"><span class="pre">wait</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Barrier.wait" title="Link to this definition">¶</a></dt><dd><p>Pass the barrier. When all the tasks party to the barrier have calledthis function, they are all unblocked simultaneously.</p><p>When a waiting or blocked task in the barrier is cancelled,this task exits the barrier which stays in the same state.If the state of the barrier is “filling”, the number of waiting taskdecreases by 1.</p><p>The return value is an integer in the range of 0 to <code class="docutils literal notranslate"><span class="pre">parties-1</span></code>, differentfor each task. This can be used to select a task to do some specialhousekeeping, e.g.:</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="o">...</span><span class="k">async</span> <span class="k">with</span> <span class="n">barrier</span> <span class="k">as</span> <span class="n">position</span><span class="p">:</span> <span class="k">if</span> <span class="n">position</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span> <span class="c1"># Only one task prints this</span> <span class="nb">print</span><span class="p">(</span><span class="s1">'End of *draining phase*'</span><span class="p">)</span></pre></div></div><p>This method may raise a <a class="reference internal" href="#asyncio.BrokenBarrierError" title="asyncio.BrokenBarrierError"><code class="xref py py-class docutils literal notranslate"><span class="pre">BrokenBarrierError</span></code></a> exception if thebarrier is broken or reset while a task is waiting.It could raise 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> if a task is cancelled.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.Barrier.reset"><em class="property"><span class="k"><span class="pre">async</span></span><span class="w"> </span></em><span class="sig-name descname"><span class="pre">reset</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Barrier.reset" title="Link to this definition">¶</a></dt><dd><p>Return the barrier to the default, empty state. Any tasks waiting on itwill receive the <a class="reference internal" href="#asyncio.BrokenBarrierError" title="asyncio.BrokenBarrierError"><code class="xref py py-class docutils literal notranslate"><span class="pre">BrokenBarrierError</span></code></a> exception.</p><p>If a barrier is broken it may be better to just leave it and create a new one.</p></dd></dl>
<dl class="py method"><dt class="sig sig-object py" id="asyncio.Barrier.abort"><em class="property"><span class="k"><span class="pre">async</span></span><span class="w"> </span></em><span class="sig-name descname"><span class="pre">abort</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Barrier.abort" title="Link to this definition">¶</a></dt><dd><p>Put the barrier into a broken state. This causes any active or futurecalls to <a class="reference internal" href="#asyncio.Barrier.wait" title="asyncio.Barrier.wait"><code class="xref py py-meth docutils literal notranslate"><span class="pre">wait()</span></code></a> to fail with the <a class="reference internal" href="#asyncio.BrokenBarrierError" title="asyncio.BrokenBarrierError"><code class="xref py py-class docutils literal notranslate"><span class="pre">BrokenBarrierError</span></code></a>.Use this for example if one of the tasks needs to abort, to avoid infinitewaiting tasks.</p></dd></dl>
<dl class="py attribute"><dt class="sig sig-object py" id="asyncio.Barrier.parties"><span class="sig-name descname"><span class="pre">parties</span></span><a class="headerlink" href="#asyncio.Barrier.parties" title="Link to this definition">¶</a></dt><dd><p>The number of tasks required to pass the barrier.</p></dd></dl>
<dl class="py attribute"><dt class="sig sig-object py" id="asyncio.Barrier.n_waiting"><span class="sig-name descname"><span class="pre">n_waiting</span></span><a class="headerlink" href="#asyncio.Barrier.n_waiting" title="Link to this definition">¶</a></dt><dd><p>The number of tasks currently waiting in the barrier while filling.</p></dd></dl>
<dl class="py attribute"><dt class="sig sig-object py" id="asyncio.Barrier.broken"><span class="sig-name descname"><span class="pre">broken</span></span><a class="headerlink" href="#asyncio.Barrier.broken" title="Link to this definition">¶</a></dt><dd><p>A boolean that is <code class="docutils literal notranslate"><span class="pre">True</span></code> if the barrier is in the broken state.</p></dd></dl>
</dd></dl>
<dl class="py exception"><dt class="sig sig-object py" id="asyncio.BrokenBarrierError"><em class="property"><span class="k"><span class="pre">exception</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">BrokenBarrierError</span></span><a class="headerlink" href="#asyncio.BrokenBarrierError" title="Link to this definition">¶</a></dt><dd><p>This exception, a subclass of <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 when the<a class="reference internal" href="#asyncio.Barrier" title="asyncio.Barrier"><code class="xref py py-class docutils literal notranslate"><span class="pre">Barrier</span></code></a> object is reset or broken.</p></dd></dl>
<hr class="docutils" /><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.9: </span>Acquiring a lock using <code class="docutils literal notranslate"><span class="pre">await</span> <span class="pre">lock</span></code> or <code class="docutils literal notranslate"><span class="pre">yield</span> <span class="pre">from</span> <span class="pre">lock</span></code> and/or<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement (<code class="docutils literal notranslate"><span class="pre">with</span> <span class="pre">await</span> <span class="pre">lock</span></code>, <code class="docutils literal notranslate"><span class="pre">with</span> <span class="pre">(yield</span> <span class="pre">from</span><span class="pre">lock)</span></code>) was removed. Use <code class="docutils literal notranslate"><span class="pre">async</span> <span class="pre">with</span> <span class="pre">lock</span></code> instead.</p></div></section></section>
<div class="clearer"></div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="Main"> <div class="sphinxsidebarwrapper"> <div> <h3><a href="../contents.html">Table of Contents</a></h3> <ul><li><a class="reference internal" href="#">Synchronization Primitives</a><ul><li><a class="reference internal" href="#lock">Lock</a></li><li><a class="reference internal" href="#event">Event</a></li><li><a class="reference internal" href="#condition">Condition</a></li><li><a class="reference internal" href="#semaphore">Semaphore</a></li><li><a class="reference internal" href="#boundedsemaphore">BoundedSemaphore</a></li><li><a class="reference internal" href="#barrier">Barrier</a></li></ul></li></ul>
</div> <div> <h4>Previous topic</h4> <p class="topless"><a href="asyncio-stream.html" title="previous chapter">Streams</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="asyncio-subprocess.html" title="next chapter">Subprocesses</a></p> </div> <script> document.addEventListener('DOMContentLoaded', () => { const title = document.querySelector('meta[property="og:title"]').content; const elements = document.querySelectorAll('.improvepage'); const pageurl = window.location.href.split('?')[0]; elements.forEach(element => { const url = new URL(element.href.split('?')[0].replace("-nojs", "")); url.searchParams.set('pagetitle', title); url.searchParams.set('pageurl', pageurl); url.searchParams.set('pagesource', "library/asyncio-sync.rst"); element.href = url.toString(); }); }); </script> <div role="note" aria-label="source link"> <h3>This page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a bug</a></li> <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li> <li> <a href="https://github.com/python/cpython/blob/main/Doc/library/asyncio-sync.rst?plain=1" rel="nofollow">Show source </a> </li> </ul> </div> </div><div id="sidebarbutton" title="Collapse sidebar"><span>«</span></div>
</div> <div class="clearer"></div> </div> <div class="related" role="navigation" aria-label="Related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="asyncio-subprocess.html" title="Subprocesses" >next</a> |</li> <li class="right" > <a href="asyncio-stream.html" title="Streams" >previous</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.15.0a6 Documentation</a> » </li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="ipc.html" >Networking and Interprocess Communication</a> »</li> <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> »</li> <li class="nav-item nav-item-this"><a href="">Synchronization Primitives</a></li> <li class="right">
<div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box"> <input type="submit" value="Go"> </form> </div> | </li> <li class="right"><label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> |</li> </ul> </div> <div class="footer"> © <a href="../copyright.html">Copyright</a> 2001 Python Software Foundation. <br> This page is licensed under the Python Software Foundation License Version 2. <br> Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. <br> See <a href="/license.html">History and License</a> for more information.<br> <br>
The Python Software Foundation is a non-profit corporation.<a href="https://www.python.org/psf/donations/">Please donate.</a><br> <br> Last updated on Mar 10, 2026 (08:58 UTC). <a href="/bugs.html">Found a bug</a>? <br>
Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3. </div>
</body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459<!DOCTYPE html>
<html lang="en" data-content_root="../"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta property="og:title" content="asyncio — Asynchronous I/O" /><meta property="og:type" content="website" /><meta property="og:url" content="https://docs.python.org/3/library/asyncio.html" /><meta property="og:site_name" content="Python documentation" /><meta property="og:description" content="Hello World!: asyncio is a library to write concurrent code using the async/await syntax. asyncio is used as a foundation for multiple Python asynchronous frameworks that provide high-performance n..." /><meta property="og:image:width" content="1146" /><meta property="og:image:height" content="600" /><meta property="og:image" content="https://docs.python.org/3.15/_images/social_previews/summary_library_asyncio_c0d82eb4.png" /><meta property="og:image:alt" content="Hello World!: asyncio is a library to write concurrent code using the async/await syntax. asyncio is used as a foundation for multiple Python asynchronous frameworks that provide high-performance n..." /><meta name="description" content="Hello World!: asyncio is a library to write concurrent code using the async/await syntax. asyncio is used as a foundation for multiple Python asynchronous frameworks that provide high-performance n..." /><meta name="twitter:card" content="summary_large_image" /><meta name="theme-color" content="#3776ab">
<title>asyncio — Asynchronous I/O — Python 3.15.0a6 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" /> <link rel="stylesheet" type="text/css" href="../_static/classic.css?v=234b1a7c" /> <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=89a2f22a" /> <link rel="stylesheet" type="text/css" href="../_static/profiling-sampling-visualization.css?v=0c2600ae" /> <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" /> <script src="../_static/documentation_options.js?v=6b7c9ff5"></script> <script src="../_static/doctools.js?v=9bcbadda"></script> <script src="../_static/sphinx_highlight.js?v=dc90522c"></script> <script src="../_static/profiling-sampling-visualization.js?v=9811ed04"></script> <script src="../_static/sidebar.js"></script> <link rel="search" type="application/opensearchdescription+xml" title="Search within Python 3.15.0a6 documentation" href="../_static/opensearch.xml"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="copyright" title="Copyright" href="../copyright.html" /> <link rel="next" title="Runners" href="asyncio-runner.html" /> <link rel="prev" title="Networking and Interprocess Communication" href="ipc.html" /> <script defer file-types="bz2,epub,zip" data-domain="docs.python.org" src="https://analytics.python.org/js/script.file-downloads.outbound-links.js"></script> <link rel="canonical" href="https://docs.python.org/3/library/asyncio.html">
<style> @media only screen { table.full-width-table { width: 100%; } } </style><link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css"> <link rel="shortcut icon" type="image/png" href="../_static/py.svg"> <script type="text/javascript" src="../_static/copybutton.js"></script> <script type="text/javascript" src="../_static/menu.js"></script> <script type="text/javascript" src="../_static/search-focus.js"></script> <script type="text/javascript" src="../_static/themetoggle.js"></script> <script type="text/javascript" src="../_static/rtd_switcher.js"></script> <meta name="readthedocs-addons-api-version" content="1">
</head><body><div class="mobile-nav"> <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation" aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu"> <nav class="nav-content" role="navigation"> <label for="menuToggler" class="toggler__label"> <span></span> </label> <span class="nav-items-wrapper"> <a href="https://www.python.org/" class="nav-logo"> <img src="../_static/py.svg" alt="Python logo"> </a> <span class="version_switcher_placeholder"></span> <form role="search" class="search" action="../search.html" method="get"> <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon"> <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> </svg> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q"> <input type="submit" value="Go"> </form> </span> </nav> <div class="menu-wrapper"> <nav class="menu" role="navigation" aria-label="main navigation"> <div class="language_switcher_placeholder"></div> <label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> <div> <h4>Previous topic</h4> <p class="topless"><a href="ipc.html" title="previous chapter">Networking and Interprocess Communication</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="asyncio-runner.html" title="next chapter">Runners</a></p> </div> <script> document.addEventListener('DOMContentLoaded', () => { const title = document.querySelector('meta[property="og:title"]').content; const elements = document.querySelectorAll('.improvepage'); const pageurl = window.location.href.split('?')[0]; elements.forEach(element => { const url = new URL(element.href.split('?')[0].replace("-nojs", "")); url.searchParams.set('pagetitle', title); url.searchParams.set('pageurl', pageurl); url.searchParams.set('pagesource', "library/asyncio.rst"); element.href = url.toString(); }); }); </script> <div role="note" aria-label="source link"> <h3>This page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a bug</a></li> <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li> <li> <a href="https://github.com/python/cpython/blob/main/Doc/library/asyncio.rst?plain=1" rel="nofollow">Show source </a> </li> </ul> </div> </nav> </div></div>
<div class="related" role="navigation" aria-label="Related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="asyncio-runner.html" title="Runners" accesskey="N">next</a> |</li> <li class="right" > <a href="ipc.html" title="Networking and Interprocess Communication" accesskey="P">previous</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.15.0a6 Documentation</a> » </li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="ipc.html" accesskey="U">Networking and Interprocess Communication</a> »</li> <li class="nav-item nav-item-this"><a href=""><code class="xref py py-mod docutils literal notranslate"><span class="pre">asyncio</span></code> — Asynchronous I/O</a></li> <li class="right">
<div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box"> <input type="submit" value="Go"> </form> </div> | </li> <li class="right"><label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> |</li> </ul> </div>
<div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <section id="module-asyncio"><span id="asyncio-asynchronous-i-o"></span><h1><code class="xref py py-mod docutils literal notranslate"><span class="pre">asyncio</span></code> — Asynchronous I/O<a class="headerlink" href="#module-asyncio" title="Link to this heading">¶</a></h1><hr class="docutils" /><aside class="sidebar"><p class="sidebar-title">Hello World!</p><div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span><span class="w"> </span><span class="nn">asyncio</span>
<span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">main</span><span class="p">():</span> <span class="nb">print</span><span class="p">(</span><span class="s1">'Hello ...'</span><span class="p">)</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> <span class="nb">print</span><span class="p">(</span><span class="s1">'... World!'</span><span class="p">)</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></pre></div></div></aside><p>asyncio is a library to write <strong>concurrent</strong> code usingthe <strong>async/await</strong> syntax.</p><p>asyncio is used as a foundation for multiple Python asynchronousframeworks that provide high-performance network and web-servers,database connection libraries, distributed task queues, etc.</p><p>asyncio is often a perfect fit for IO-bound and high-level<strong>structured</strong> network code.</p><div class="admonition seealso"><p class="admonition-title">See also</p><dl class="simple"><dt><a class="reference internal" href="../howto/a-conceptual-overview-of-asyncio.html#a-conceptual-overview-of-asyncio"><span class="std std-ref">A conceptual overview of asyncio</span></a></dt><dd><p>Explanation of the fundamentals of asyncio.</p></dd></dl></div><p>asyncio provides a set of <strong>high-level</strong> APIs to:</p><ul class="simple"><li><p><a class="reference internal" href="asyncio-task.html#coroutine"><span class="std std-ref">run Python coroutines</span></a> concurrently andhave full control over their execution;</p></li><li><p>perform <a class="reference internal" href="asyncio-stream.html#asyncio-streams"><span class="std std-ref">network IO and IPC</span></a>;</p></li><li><p>control <a class="reference internal" href="asyncio-subprocess.html#asyncio-subprocess"><span class="std std-ref">subprocesses</span></a>;</p></li><li><p>distribute tasks via <a class="reference internal" href="asyncio-queue.html#asyncio-queues"><span class="std std-ref">queues</span></a>;</p></li><li><p><a class="reference internal" href="asyncio-sync.html#asyncio-sync"><span class="std std-ref">synchronize</span></a> concurrent code;</p></li></ul><p>Additionally, there are <strong>low-level</strong> APIs for<em>library and framework developers</em> to:</p><ul class="simple"><li><p>create and manage <a class="reference internal" href="asyncio-eventloop.html#asyncio-event-loop"><span class="std std-ref">event loops</span></a>, whichprovide asynchronous APIs for <a class="reference internal" href="asyncio-eventloop.html#loop-create-server"><span class="std std-ref">networking</span></a>,running <a class="reference internal" href="asyncio-eventloop.html#loop-subprocess-exec"><span class="std std-ref">subprocesses</span></a>,handling <a class="reference internal" href="asyncio-eventloop.html#loop-add-signal-handler"><span class="std std-ref">OS signals</span></a>, etc;</p></li><li><p>implement efficient protocols using<a class="reference internal" href="asyncio-protocol.html#asyncio-transports-protocols"><span class="std std-ref">transports</span></a>;</p></li><li><p><a class="reference internal" href="asyncio-future.html#asyncio-futures"><span class="std std-ref">bridge</span></a> callback-based libraries and codewith async/await syntax.</p></li></ul><div class="availability docutils container"><p><a class="reference internal" href="intro.html#availability"><span class="std std-ref">Availability</span></a>: not WASI.</p><p>This module does not work or is not available on WebAssembly. See<a class="reference internal" href="intro.html#wasm-availability"><span class="std std-ref">WebAssembly platforms</span></a> for more information.</p></div><p class="rubric" id="asyncio-cli">asyncio REPL</p><p>You can experiment with an <code class="docutils literal notranslate"><span class="pre">asyncio</span></code> concurrent context in the <a class="reference internal" href="../glossary.html#term-REPL"><span class="xref std std-term">REPL</span></a>:</p><div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="go">$ python -m asyncio</span><span class="go">asyncio REPL ...</span><span class="go">Use "await" directly instead of "asyncio.run()".</span><span class="go">Type "help", "copyright", "credits" or "license" for more information.</span><span class="gp">>>> </span><span class="kn">import</span><span class="w"> </span><span class="nn">asyncio</span><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">10</span><span class="p">,</span> <span class="n">result</span><span class="o">=</span><span class="s1">'hello'</span><span class="p">)</span><span class="go">'hello'</span></pre></div></div><p>This REPL provides limited compatibility with <span class="target" id="index-0"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHON_BASIC_REPL"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHON_BASIC_REPL</span></code></a>.It is recommended that the default REPL is usedfor full functionality and the latest features.</p><p class="audit-hook" id="audit_event_cpython_run_stdin_2">Raises an <a class="reference internal" href="sys.html#auditing"><span class="std std-ref">auditing event</span></a> <code class="docutils literal notranslate"><span class="pre">cpython.run_stdin</span></code> with no arguments.</p><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.12.5: </span>(also 3.11.10, 3.10.15, 3.9.20, and 3.8.20)Emits audit events.</p></div><div class="versionchanged"><p><span class="versionmodified changed">Changed in version 3.13: </span>Uses PyREPL if possible, in which case <span class="target" id="index-1"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONSTARTUP"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONSTARTUP</span></code></a> isalso executed. Emits audit events.</p></div><p class="rubric">Reference</p><div class="toctree-wrapper compound"><p class="caption" role="heading"><span class="caption-text">High-level APIs</span></p><ul><li class="toctree-l1"><a class="reference internal" href="asyncio-runner.html">Runners</a></li><li class="toctree-l1"><a class="reference internal" href="asyncio-task.html">Coroutines and Tasks</a></li><li class="toctree-l1"><a class="reference internal" href="asyncio-stream.html">Streams</a></li><li class="toctree-l1"><a class="reference internal" href="asyncio-sync.html">Synchronization Primitives</a></li><li class="toctree-l1"><a class="reference internal" href="asyncio-subprocess.html">Subprocesses</a></li><li class="toctree-l1"><a class="reference internal" href="asyncio-queue.html">Queues</a></li><li class="toctree-l1"><a class="reference internal" href="asyncio-exceptions.html">Exceptions</a></li><li class="toctree-l1"><a class="reference internal" href="asyncio-graph.html">Call Graph Introspection</a></li></ul></div><div class="toctree-wrapper compound"><p class="caption" role="heading"><span class="caption-text">Low-level APIs</span></p><ul><li class="toctree-l1"><a class="reference internal" href="asyncio-eventloop.html">Event Loop</a></li><li class="toctree-l1"><a class="reference internal" href="asyncio-future.html">Futures</a></li><li class="toctree-l1"><a class="reference internal" href="asyncio-protocol.html">Transports and Protocols</a></li><li class="toctree-l1"><a class="reference internal" href="asyncio-policy.html">Policies</a></li><li class="toctree-l1"><a class="reference internal" href="asyncio-platforms.html">Platform Support</a></li><li class="toctree-l1"><a class="reference internal" href="asyncio-extending.html">Extending</a></li></ul></div><div class="toctree-wrapper compound"><p class="caption" role="heading"><span class="caption-text">Guides and Tutorials</span></p><ul><li class="toctree-l1"><a class="reference internal" href="asyncio-api-index.html">High-level API Index</a></li><li class="toctree-l1"><a class="reference internal" href="asyncio-llapi-index.html">Low-level API Index</a></li><li class="toctree-l1"><a class="reference internal" href="asyncio-dev.html">Developing with asyncio</a></li></ul></div><div class="admonition note"><p class="admonition-title">Note</p><p>The source code for asyncio can be found in <a class="extlink-source reference external" href="https://github.com/python/cpython/tree/main/Lib/asyncio/">Lib/asyncio/</a>.</p></div></section>
<div class="clearer"></div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="Main"> <div class="sphinxsidebarwrapper"> <div> <h4>Previous topic</h4> <p class="topless"><a href="ipc.html" title="previous chapter">Networking and Interprocess Communication</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="asyncio-runner.html" title="next chapter">Runners</a></p> </div> <script> document.addEventListener('DOMContentLoaded', () => { const title = document.querySelector('meta[property="og:title"]').content; const elements = document.querySelectorAll('.improvepage'); const pageurl = window.location.href.split('?')[0]; elements.forEach(element => { const url = new URL(element.href.split('?')[0].replace("-nojs", "")); url.searchParams.set('pagetitle', title); url.searchParams.set('pageurl', pageurl); url.searchParams.set('pagesource', "library/asyncio.rst"); element.href = url.toString(); }); }); </script> <div role="note" aria-label="source link"> <h3>This page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a bug</a></li> <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li> <li> <a href="https://github.com/python/cpython/blob/main/Doc/library/asyncio.rst?plain=1" rel="nofollow">Show source </a> </li> </ul> </div> </div><div id="sidebarbutton" title="Collapse sidebar"><span>«</span></div>
</div> <div class="clearer"></div> </div> <div class="related" role="navigation" aria-label="Related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="asyncio-runner.html" title="Runners" >next</a> |</li> <li class="right" > <a href="ipc.html" title="Networking and Interprocess Communication" >previous</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.15.0a6 Documentation</a> » </li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="ipc.html" >Networking and Interprocess Communication</a> »</li> <li class="nav-item nav-item-this"><a href=""><code class="xref py py-mod docutils literal notranslate"><span class="pre">asyncio</span></code> — Asynchronous I/O</a></li> <li class="right">
<div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box"> <input type="submit" value="Go"> </form> </div> | </li> <li class="right"><label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> |</li> </ul> </div> <div class="footer"> © <a href="../copyright.html">Copyright</a> 2001 Python Software Foundation. <br> This page is licensed under the Python Software Foundation License Version 2. <br> Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. <br> See <a href="/license.html">History and License</a> for more information.<br> <br>
The Python Software Foundation is a non-profit corporation.<a href="https://www.python.org/psf/donations/">Please donate.</a><br> <br> Last updated on Mar 10, 2026 (08:58 UTC). <a href="/bugs.html">Found a bug</a>? <br>
Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3. </div>
</body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354<!DOCTYPE html>
<html lang="en" data-content_root="../"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta property="og:title" content="asyncore — Asynchronous socket handler" /><meta property="og:type" content="website" /><meta property="og:url" content="https://docs.python.org/3/library/asyncore.html" /><meta property="og:site_name" content="Python documentation" /><meta property="og:description" content="This module is no longer part of the Python standard library. It was removed in Python 3.12 after being deprecated in Python 3.6. The removal was decided in PEP 594. Applications should use the asy..." /><meta property="og:image:width" content="1146" /><meta property="og:image:height" content="600" /><meta property="og:image" content="https://docs.python.org/3.15/_images/social_previews/summary_library_asyncore_61d4cad8.png" /><meta property="og:image:alt" content="This module is no longer part of the Python standard library. It was removed in Python 3.12 after being deprecated in Python 3.6. The removal was decided in PEP 594. Applications should use the asy..." /><meta name="description" content="This module is no longer part of the Python standard library. It was removed in Python 3.12 after being deprecated in Python 3.6. The removal was decided in PEP 594. Applications should use the asy..." /><meta name="twitter:card" content="summary_large_image" /><meta name="theme-color" content="#3776ab">
<title>asyncore — Asynchronous socket handler — Python 3.15.0a6 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" /> <link rel="stylesheet" type="text/css" href="../_static/classic.css?v=234b1a7c" /> <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=89a2f22a" /> <link rel="stylesheet" type="text/css" href="../_static/profiling-sampling-visualization.css?v=0c2600ae" /> <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" /> <script src="../_static/documentation_options.js?v=6b7c9ff5"></script> <script src="../_static/doctools.js?v=9bcbadda"></script> <script src="../_static/sphinx_highlight.js?v=dc90522c"></script> <script src="../_static/profiling-sampling-visualization.js?v=9811ed04"></script> <script src="../_static/sidebar.js"></script> <link rel="search" type="application/opensearchdescription+xml" title="Search within Python 3.15.0a6 documentation" href="../_static/opensearch.xml"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="copyright" title="Copyright" href="../copyright.html" /> <link rel="next" title="audioop — Manipulate raw audio data" href="audioop.html" /> <link rel="prev" title="asynchat — Asynchronous socket command/response handler" href="asynchat.html" /> <script defer file-types="bz2,epub,zip" data-domain="docs.python.org" src="https://analytics.python.org/js/script.file-downloads.outbound-links.js"></script> <link rel="canonical" href="https://docs.python.org/3/library/asyncore.html">
<style> @media only screen { table.full-width-table { width: 100%; } } </style><link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css"> <link rel="shortcut icon" type="image/png" href="../_static/py.svg"> <script type="text/javascript" src="../_static/copybutton.js"></script> <script type="text/javascript" src="../_static/menu.js"></script> <script type="text/javascript" src="../_static/search-focus.js"></script> <script type="text/javascript" src="../_static/themetoggle.js"></script> <script type="text/javascript" src="../_static/rtd_switcher.js"></script> <meta name="readthedocs-addons-api-version" content="1">
</head><body><div class="mobile-nav"> <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation" aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu"> <nav class="nav-content" role="navigation"> <label for="menuToggler" class="toggler__label"> <span></span> </label> <span class="nav-items-wrapper"> <a href="https://www.python.org/" class="nav-logo"> <img src="../_static/py.svg" alt="Python logo"> </a> <span class="version_switcher_placeholder"></span> <form role="search" class="search" action="../search.html" method="get"> <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon"> <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> </svg> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q"> <input type="submit" value="Go"> </form> </span> </nav> <div class="menu-wrapper"> <nav class="menu" role="navigation" aria-label="main navigation"> <div class="language_switcher_placeholder"></div> <label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> <div> <h4>Previous topic</h4> <p class="topless"><a href="asynchat.html" title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">asynchat</span></code> — Asynchronous socket command/response handler</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="audioop.html" title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">audioop</span></code> — Manipulate raw audio data</a></p> </div> <script> document.addEventListener('DOMContentLoaded', () => { const title = document.querySelector('meta[property="og:title"]').content; const elements = document.querySelectorAll('.improvepage'); const pageurl = window.location.href.split('?')[0]; elements.forEach(element => { const url = new URL(element.href.split('?')[0].replace("-nojs", "")); url.searchParams.set('pagetitle', title); url.searchParams.set('pageurl', pageurl); url.searchParams.set('pagesource', "library/asyncore.rst"); element.href = url.toString(); }); }); </script> <div role="note" aria-label="source link"> <h3>This page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a bug</a></li> <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li> <li> <a href="https://github.com/python/cpython/blob/main/Doc/library/asyncore.rst?plain=1" rel="nofollow">Show source </a> </li> </ul> </div> </nav> </div></div>
<div class="related" role="navigation" aria-label="Related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="audioop.html" title="audioop — Manipulate raw audio data" accesskey="N">next</a> |</li> <li class="right" > <a href="asynchat.html" title="asynchat — Asynchronous socket command/response handler" accesskey="P">previous</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.15.0a6 Documentation</a> » </li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="removed.html" accesskey="U">Removed Modules</a> »</li> <li class="nav-item nav-item-this"><a href=""><code class="xref py py-mod docutils literal notranslate"><span class="pre">asyncore</span></code> — Asynchronous socket handler</a></li> <li class="right">
<div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box"> <input type="submit" value="Go"> </form> </div> | </li> <li class="right"><label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> |</li> </ul> </div>
<div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <section id="module-asyncore"><span id="asyncore-asynchronous-socket-handler"></span><h1><code class="xref py py-mod docutils literal notranslate"><span class="pre">asyncore</span></code> — Asynchronous socket handler<a class="headerlink" href="#module-asyncore" title="Link to this heading">¶</a></h1><div class="deprecated-removed"><p><span class="versionmodified removed">Deprecated since version 3.6, removed in version 3.12.</span></p></div><p>This module is no longer part of the Python standard library.It was <a class="reference internal" href="../whatsnew/3.12.html#whatsnew312-removed"><span class="std std-ref">removed in Python 3.12</span></a> afterbeing deprecated in Python 3.6. The removal was decided in <span class="target" id="index-0"></span><a class="pep reference external" href="https://peps.python.org/pep-0594/"><strong>PEP 594</strong></a>.</p><p>Applications should use the <a class="reference internal" href="asyncio.html#module-asyncio" title="asyncio: Asynchronous I/O."><code class="xref py py-mod docutils literal notranslate"><span class="pre">asyncio</span></code></a> module instead.</p><p>The last version of Python that provided the <code class="xref py py-mod docutils literal notranslate"><span class="pre">asyncore</span></code> module was<a class="reference external" href="https://docs.python.org/3.11/library/asyncore.html">Python 3.11</a>.</p></section>
<div class="clearer"></div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="Main"> <div class="sphinxsidebarwrapper"> <div> <h4>Previous topic</h4> <p class="topless"><a href="asynchat.html" title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">asynchat</span></code> — Asynchronous socket command/response handler</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="audioop.html" title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">audioop</span></code> — Manipulate raw audio data</a></p> </div> <script> document.addEventListener('DOMContentLoaded', () => { const title = document.querySelector('meta[property="og:title"]').content; const elements = document.querySelectorAll('.improvepage'); const pageurl = window.location.href.split('?')[0]; elements.forEach(element => { const url = new URL(element.href.split('?')[0].replace("-nojs", "")); url.searchParams.set('pagetitle', title); url.searchParams.set('pageurl', pageurl); url.searchParams.set('pagesource', "library/asyncore.rst"); element.href = url.toString(); }); }); </script> <div role="note" aria-label="source link"> <h3>This page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a bug</a></li> <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li> <li> <a href="https://github.com/python/cpython/blob/main/Doc/library/asyncore.rst?plain=1" rel="nofollow">Show source </a> </li> </ul> </div> </div><div id="sidebarbutton" title="Collapse sidebar"><span>«</span></div>
</div> <div class="clearer"></div> </div> <div class="related" role="navigation" aria-label="Related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="audioop.html" title="audioop — Manipulate raw audio data" >next</a> |</li> <li class="right" > <a href="asynchat.html" title="asynchat — Asynchronous socket command/response handler" >previous</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.15.0a6 Documentation</a> » </li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="removed.html" >Removed Modules</a> »</li> <li class="nav-item nav-item-this"><a href=""><code class="xref py py-mod docutils literal notranslate"><span class="pre">asyncore</span></code> — Asynchronous socket handler</a></li> <li class="right">
<div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box"> <input type="submit" value="Go"> </form> </div> | </li> <li class="right"><label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select></label> |</li> </ul> </div> <div class="footer"> © <a href="../copyright.html">Copyright</a> 2001 Python Software Foundation. <br> This page is licensed under the Python Software Foundation License Version 2. <br> Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. <br> See <a href="/license.html">History and License</a> for more information.<br> <br>
The Python Software Foundation is a non-profit corporation.<a href="https://www.python.org/psf/donations/">Please donate.</a><br> <br> Last updated on Mar 10, 2026 (08:58 UTC). <a href="/bugs.html">Found a bug</a>? <br>
Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3. </div>
</body></html>.dockerignoreAdded+10
DockerfileAdded+18
docs/__future__.htmlAdded+560
docs/__main__.htmlAdded+702
docs/_thread.htmlAdded+553
docs/abc.htmlAdded+695
docs/aifc.htmlAdded+353
docs/allos.htmlAdded+513
docs/annotationlib.htmlAdded
docs/archiving.htmlAdded+429
docs/argparse.htmlAdded
docs/array.htmlAdded+700
docs/ast.htmlAdded
docs/asynchat.htmlAdded+354
docs/asyncio-api-index.htmlAdded+597
docs/asyncio-dev.htmlAdded+587
docs/asyncio-eventloop.htmlAdded
docs/asyncio-exceptions.htmlAdded+420
docs/asyncio-extending.htmlAdded+454
docs/asyncio-future.htmlAdded+636
docs/asyncio-graph.htmlAdded+494
docs/asyncio-llapi-index.htmlAdded+935
docs/asyncio-platforms.htmlAdded+450
docs/asyncio-policy.htmlAdded+528
docs/asyncio-protocol.htmlAdded
docs/asyncio-queue.htmlAdded+626
docs/asyncio-runner.htmlAdded+534
docs/asyncio-stream.htmlAdded+941
docs/asyncio-subprocess.htmlAdded+716
docs/asyncio-sync.htmlAdded+844
docs/asyncio-task.htmlAdded
docs/asyncio.htmlAdded+459
docs/asyncore.htmlAdded+354
docs/atexit.htmlAdded
docs/audioop.htmlAdded
docs/audit_events.htmlAdded
docs/base64.htmlAdded
docs/bdb.htmlAdded
docs/binary.htmlAdded
docs/binascii.htmlAdded
docs/bisect.htmlAdded
docs/builtins.htmlAdded
docs/bz2.htmlAdded
docs/calendar.htmlAdded
docs/cgi.htmlAdded
docs/cgitb.htmlAdded
docs/chunk.htmlAdded
docs/cmath.htmlAdded
docs/cmd.htmlAdded
docs/cmdline.htmlAdded