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

1377 line
126KB

  1. <!DOCTYPE html>
  2. <html lang="en" data-content_root="../">
  3. <head>
  4. <meta charset="utf-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" />
  6. <meta property="og:title" content="contextlib — Utilities for with-statement contexts" />
  7. <meta property="og:type" content="website" />
  8. <meta property="og:url" content="https://docs.python.org/3/library/contextlib.html" />
  9. <meta property="og:site_name" content="Python documentation" />
  10. <meta property="og:description" content="Source code: Lib/contextlib.py This module provides utilities for common tasks involving the with statement. For more information see also Context Manager Types and With Statement Context Managers...." />
  11. <meta property="og:image" content="https://docs.python.org/3/_static/og-image.png" />
  12. <meta property="og:image:alt" content="Python documentation" />
  13. <meta name="description" content="Source code: Lib/contextlib.py This module provides utilities for common tasks involving the with statement. For more information see also Context Manager Types and With Statement Context Managers...." />
  14. <meta property="og:image:width" content="200" />
  15. <meta property="og:image:height" content="200" />
  16. <meta name="theme-color" content="#3776ab" />
  17. <title>contextlib — Utilities for with-statement contexts &#8212; Python 3.12.3 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">
  18. <link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=80d5e7a1" />
  19. <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=bb723527" />
  20. <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=b20cc3f5" />
  21. <script src="../_static/documentation_options.js?v=2c828074"></script>
  22. <script src="../_static/doctools.js?v=888ff710"></script>
  23. <script src="../_static/sphinx_highlight.js?v=dc90522c"></script>
  24. <script src="../_static/sidebar.js"></script>
  25. <link rel="search" type="application/opensearchdescription+xml"
  26. title="Search within Python 3.12.3 documentation"
  27. href="../_static/opensearch.xml"/>
  28. <link rel="author" title="About these documents" href="../about.html" />
  29. <link rel="index" title="Index" href="../genindex.html" />
  30. <link rel="search" title="Search" href="../search.html" />
  31. <link rel="copyright" title="Copyright" href="../copyright.html" />
  32. <link rel="next" title="abc — Abstract Base Classes" href="abc.html" />
  33. <link rel="prev" title="dataclasses — Data Classes" href="dataclasses.html" />
  34. <link rel="canonical" href="https://docs.python.org/3/library/contextlib.html" />
  35. <style>
  36. @media only screen {
  37. table.full-width-table {
  38. width: 100%;
  39. }
  40. }
  41. </style>
  42. <link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">
  43. <link rel="shortcut icon" type="image/png" href="../_static/py.svg" />
  44. <script type="text/javascript" src="../_static/copybutton.js"></script>
  45. <script type="text/javascript" src="../_static/menu.js"></script>
  46. <script type="text/javascript" src="../_static/search-focus.js"></script>
  47. <script type="text/javascript" src="../_static/themetoggle.js"></script>
  48. </head>
  49. <body>
  50. <div class="mobile-nav">
  51. <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"
  52. aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu" />
  53. <nav class="nav-content" role="navigation">
  54. <label for="menuToggler" class="toggler__label">
  55. <span></span>
  56. </label>
  57. <span class="nav-items-wrapper">
  58. <a href="https://www.python.org/" class="nav-logo">
  59. <img src="../_static/py.svg" alt="Python logo"/>
  60. </a>
  61. <span class="version_switcher_placeholder"></span>
  62. <form role="search" class="search" action="../search.html" method="get">
  63. <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">
  64. <path fill-rule="nonzero" fill="currentColor" d="M15.5 14h-.79l-.28-.27a6.5 6.5 0 001.48-5.34c-.47-2.78-2.79-5-5.59-5.34a6.505 6.505 0 00-7.27 7.27c.34 2.8 2.56 5.12 5.34 5.59a6.5 6.5 0 005.34-1.48l.27.28v.79l4.25 4.25c.41.41 1.08.41 1.49 0 .41-.41.41-1.08 0-1.49L15.5 14zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"></path>
  65. </svg>
  66. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
  67. <input type="submit" value="Go"/>
  68. </form>
  69. </span>
  70. </nav>
  71. <div class="menu-wrapper">
  72. <nav class="menu" role="navigation" aria-label="main navigation">
  73. <div class="language_switcher_placeholder"></div>
  74. <label class="theme-selector-label">
  75. Theme
  76. <select class="theme-selector" oninput="activateTheme(this.value)">
  77. <option value="auto" selected>Auto</option>
  78. <option value="light">Light</option>
  79. <option value="dark">Dark</option>
  80. </select>
  81. </label>
  82. <div>
  83. <h3><a href="../contents.html">Table of Contents</a></h3>
  84. <ul>
  85. <li><a class="reference internal" href="#"><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><ul>
  86. <li><a class="reference internal" href="#utilities">Utilities</a></li>
  87. <li><a class="reference internal" href="#examples-and-recipes">Examples and Recipes</a><ul>
  88. <li><a class="reference internal" href="#supporting-a-variable-number-of-context-managers">Supporting a variable number of context managers</a></li>
  89. <li><a class="reference internal" href="#catching-exceptions-from-enter-methods">Catching exceptions from <code class="docutils literal notranslate"><span class="pre">__enter__</span></code> methods</a></li>
  90. <li><a class="reference internal" href="#cleaning-up-in-an-enter-implementation">Cleaning up in an <code class="docutils literal notranslate"><span class="pre">__enter__</span></code> implementation</a></li>
  91. <li><a class="reference internal" href="#replacing-any-use-of-try-finally-and-flag-variables">Replacing any use of <code class="docutils literal notranslate"><span class="pre">try-finally</span></code> and flag variables</a></li>
  92. <li><a class="reference internal" href="#using-a-context-manager-as-a-function-decorator">Using a context manager as a function decorator</a></li>
  93. </ul>
  94. </li>
  95. <li><a class="reference internal" href="#single-use-reusable-and-reentrant-context-managers">Single use, reusable and reentrant context managers</a><ul>
  96. <li><a class="reference internal" href="#reentrant-context-managers">Reentrant context managers</a></li>
  97. <li><a class="reference internal" href="#reusable-context-managers">Reusable context managers</a></li>
  98. </ul>
  99. </li>
  100. </ul>
  101. </li>
  102. </ul>
  103. </div>
  104. <div>
  105. <h4>Previous topic</h4>
  106. <p class="topless"><a href="dataclasses.html"
  107. title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">dataclasses</span></code> — Data Classes</a></p>
  108. </div>
  109. <div>
  110. <h4>Next topic</h4>
  111. <p class="topless"><a href="abc.html"
  112. title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">abc</span></code> — Abstract Base Classes</a></p>
  113. </div>
  114. <div role="note" aria-label="source link">
  115. <h3>This Page</h3>
  116. <ul class="this-page-menu">
  117. <li><a href="../bugs.html">Report a Bug</a></li>
  118. <li>
  119. <a href="https://github.com/python/cpython/blob/main/Doc/library/contextlib.rst"
  120. rel="nofollow">Show Source
  121. </a>
  122. </li>
  123. </ul>
  124. </div>
  125. </nav>
  126. </div>
  127. </div>
  128. <div class="related" role="navigation" aria-label="related navigation">
  129. <h3>Navigation</h3>
  130. <ul>
  131. <li class="right" style="margin-right: 10px">
  132. <a href="../genindex.html" title="General Index"
  133. accesskey="I">index</a></li>
  134. <li class="right" >
  135. <a href="../py-modindex.html" title="Python Module Index"
  136. >modules</a> |</li>
  137. <li class="right" >
  138. <a href="abc.html" title="abc — Abstract Base Classes"
  139. accesskey="N">next</a> |</li>
  140. <li class="right" >
  141. <a href="dataclasses.html" title="dataclasses — Data Classes"
  142. accesskey="P">previous</a> |</li>
  143. <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  144. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  145. <li class="switchers">
  146. <div class="language_switcher_placeholder"></div>
  147. <div class="version_switcher_placeholder"></div>
  148. </li>
  149. <li>
  150. </li>
  151. <li id="cpython-language-and-version">
  152. <a href="../index.html">3.12.3 Documentation</a> &#187;
  153. </li>
  154. <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
  155. <li class="nav-item nav-item-2"><a href="python.html" accesskey="U">Python Runtime Services</a> &#187;</li>
  156. <li class="nav-item nav-item-this"><a href=""><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></li>
  157. <li class="right">
  158. <div class="inline-search" role="search">
  159. <form class="inline-search" action="../search.html" method="get">
  160. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
  161. <input type="submit" value="Go" />
  162. </form>
  163. </div>
  164. |
  165. </li>
  166. <li class="right">
  167. <label class="theme-selector-label">
  168. Theme
  169. <select class="theme-selector" oninput="activateTheme(this.value)">
  170. <option value="auto" selected>Auto</option>
  171. <option value="light">Light</option>
  172. <option value="dark">Dark</option>
  173. </select>
  174. </label> |</li>
  175. </ul>
  176. </div>
  177. <div class="document">
  178. <div class="documentwrapper">
  179. <div class="bodywrapper">
  180. <div class="body" role="main">
  181. <section id="module-contextlib">
  182. <span id="contextlib-utilities-for-with-statement-contexts"></span><h1><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 class="headerlink" href="#module-contextlib" title="Link to this heading">¶</a></h1>
  183. <p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/contextlib.py">Lib/contextlib.py</a></p>
  184. <hr class="docutils" />
  185. <p>This module provides utilities for common tasks involving 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>
  186. statement. For more information see also <a class="reference internal" href="stdtypes.html#typecontextmanager"><span class="std std-ref">Context Manager Types</span></a> and
  187. <a class="reference internal" href="../reference/datamodel.html#context-managers"><span class="std std-ref">With Statement Context Managers</span></a>.</p>
  188. <section id="utilities">
  189. <h2>Utilities<a class="headerlink" href="#utilities" title="Link to this heading">¶</a></h2>
  190. <p>Functions and classes provided:</p>
  191. <dl class="py class">
  192. <dt class="sig sig-object py" id="contextlib.AbstractContextManager">
  193. <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">contextlib.</span></span><span class="sig-name descname"><span class="pre">AbstractContextManager</span></span><a class="headerlink" href="#contextlib.AbstractContextManager" title="Link to this definition">¶</a></dt>
  194. <dd><p>An <a class="reference internal" href="../glossary.html#term-abstract-base-class"><span class="xref std std-term">abstract base class</span></a> for classes that implement
  195. <a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">object.__enter__()</span></code></a> and <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">object.__exit__()</span></code></a>. A default
  196. implementation for <a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">object.__enter__()</span></code></a> is provided which returns
  197. <code class="docutils literal notranslate"><span class="pre">self</span></code> while <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">object.__exit__()</span></code></a> is an abstract method which by default
  198. returns <code class="docutils literal notranslate"><span class="pre">None</span></code>. See also the definition of <a class="reference internal" href="stdtypes.html#typecontextmanager"><span class="std std-ref">Context Manager Types</span></a>.</p>
  199. <div class="versionadded">
  200. <p><span class="versionmodified added">New in version 3.6.</span></p>
  201. </div>
  202. </dd></dl>
  203. <dl class="py class">
  204. <dt class="sig sig-object py" id="contextlib.AbstractAsyncContextManager">
  205. <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">contextlib.</span></span><span class="sig-name descname"><span class="pre">AbstractAsyncContextManager</span></span><a class="headerlink" href="#contextlib.AbstractAsyncContextManager" title="Link to this definition">¶</a></dt>
  206. <dd><p>An <a class="reference internal" href="../glossary.html#term-abstract-base-class"><span class="xref std std-term">abstract base class</span></a> for classes that implement
  207. <a class="reference internal" href="../reference/datamodel.html#object.__aenter__" title="object.__aenter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">object.__aenter__()</span></code></a> and <a class="reference internal" href="../reference/datamodel.html#object.__aexit__" title="object.__aexit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">object.__aexit__()</span></code></a>. A default
  208. implementation for <a class="reference internal" href="../reference/datamodel.html#object.__aenter__" title="object.__aenter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">object.__aenter__()</span></code></a> is provided which returns
  209. <code class="docutils literal notranslate"><span class="pre">self</span></code> while <a class="reference internal" href="../reference/datamodel.html#object.__aexit__" title="object.__aexit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">object.__aexit__()</span></code></a> is an abstract method which by default
  210. returns <code class="docutils literal notranslate"><span class="pre">None</span></code>. See also the definition of
  211. <a class="reference internal" href="../reference/datamodel.html#async-context-managers"><span class="std std-ref">Asynchronous Context Managers</span></a>.</p>
  212. <div class="versionadded">
  213. <p><span class="versionmodified added">New in version 3.7.</span></p>
  214. </div>
  215. </dd></dl>
  216. <dl class="py function">
  217. <dt class="sig sig-object py" id="contextlib.contextmanager">
  218. <span class="sig-prename descclassname"><span class="pre">&#64;</span></span><span class="sig-prename descclassname"><span class="pre">contextlib.</span></span><span class="sig-name descname"><span class="pre">contextmanager</span></span><a class="headerlink" href="#contextlib.contextmanager" title="Link to this definition">¶</a></dt>
  219. <dd><p>This function is a <a class="reference internal" href="../glossary.html#term-decorator"><span class="xref std std-term">decorator</span></a> that can be used to define a factory
  220. function for <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 context managers, without needing to
  221. create a class or separate <a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> and <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> methods.</p>
  222. <p>While many objects natively support use in with statements, sometimes a
  223. resource needs to be managed that isn’t a context manager in its own right,
  224. and doesn’t implement a <code class="docutils literal notranslate"><span class="pre">close()</span></code> method for use with <code class="docutils literal notranslate"><span class="pre">contextlib.closing</span></code></p>
  225. <p>An abstract example would be the following to ensure correct resource
  226. management:</p>
  227. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">contextlib</span> <span class="kn">import</span> <span class="n">contextmanager</span>
  228. <span class="nd">@contextmanager</span>
  229. <span class="k">def</span> <span class="nf">managed_resource</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwds</span><span class="p">):</span>
  230. <span class="c1"># Code to acquire resource, e.g.:</span>
  231. <span class="n">resource</span> <span class="o">=</span> <span class="n">acquire_resource</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwds</span><span class="p">)</span>
  232. <span class="k">try</span><span class="p">:</span>
  233. <span class="k">yield</span> <span class="n">resource</span>
  234. <span class="k">finally</span><span class="p">:</span>
  235. <span class="c1"># Code to release resource, e.g.:</span>
  236. <span class="n">release_resource</span><span class="p">(</span><span class="n">resource</span><span class="p">)</span>
  237. </pre></div>
  238. </div>
  239. <p>The function can then be used like this:</p>
  240. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">with</span> <span class="n">managed_resource</span><span class="p">(</span><span class="n">timeout</span><span class="o">=</span><span class="mi">3600</span><span class="p">)</span> <span class="k">as</span> <span class="n">resource</span><span class="p">:</span>
  241. <span class="gp">... </span> <span class="c1"># Resource is released at the end of this block,</span>
  242. <span class="gp">... </span> <span class="c1"># even if code in the block raises an exception</span>
  243. </pre></div>
  244. </div>
  245. <p>The function being decorated must return a <a class="reference internal" href="../glossary.html#term-generator"><span class="xref std std-term">generator</span></a>-iterator when
  246. called. This iterator must yield exactly one value, which will be bound to
  247. the targets in 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’s <code class="xref std std-keyword docutils literal notranslate"><span class="pre">as</span></code> clause, if any.</p>
  248. <p>At the point where the generator yields, the block nested in 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>
  249. statement is executed. The generator is then resumed after the block is exited.
  250. If an unhandled exception occurs in the block, it is reraised inside the
  251. generator at the point where the yield occurred. Thus, you can use a
  252. <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#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</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> statement to trap
  253. the error (if any), or ensure that some cleanup takes place. If an exception is
  254. trapped merely in order to log it or to perform some action (rather than to
  255. suppress it entirely), the generator must reraise that exception. Otherwise the
  256. generator context manager will indicate to the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code> statement that
  257. the exception has been handled, and execution will resume with the statement
  258. immediately following the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code> statement.</p>
  259. <p><a class="reference internal" href="#contextlib.contextmanager" title="contextlib.contextmanager"><code class="xref py py-func docutils literal notranslate"><span class="pre">contextmanager()</span></code></a> uses <a class="reference internal" href="#contextlib.ContextDecorator" title="contextlib.ContextDecorator"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContextDecorator</span></code></a> so the context managers
  260. it creates can be used as decorators as well as in <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> statements.
  261. When used as a decorator, a new generator instance is implicitly created on
  262. each function call (this allows the otherwise “one-shot” context managers
  263. created by <a class="reference internal" href="#contextlib.contextmanager" title="contextlib.contextmanager"><code class="xref py py-func docutils literal notranslate"><span class="pre">contextmanager()</span></code></a> to meet the requirement that context
  264. managers support multiple invocations in order to be used as decorators).</p>
  265. <div class="versionchanged">
  266. <p><span class="versionmodified changed">Changed in version 3.2: </span>Use of <a class="reference internal" href="#contextlib.ContextDecorator" title="contextlib.ContextDecorator"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContextDecorator</span></code></a>.</p>
  267. </div>
  268. </dd></dl>
  269. <dl class="py function">
  270. <dt class="sig sig-object py" id="contextlib.asynccontextmanager">
  271. <span class="sig-prename descclassname"><span class="pre">&#64;</span></span><span class="sig-prename descclassname"><span class="pre">contextlib.</span></span><span class="sig-name descname"><span class="pre">asynccontextmanager</span></span><a class="headerlink" href="#contextlib.asynccontextmanager" title="Link to this definition">¶</a></dt>
  272. <dd><blockquote>
  273. <div><p>Similar to <a class="reference internal" href="#contextlib.contextmanager" title="contextlib.contextmanager"><code class="xref py py-func docutils literal notranslate"><span class="pre">contextmanager()</span></code></a>, but creates an
  274. <a class="reference internal" href="../reference/datamodel.html#async-context-managers"><span class="std std-ref">asynchronous context manager</span></a>.</p>
  275. <p>This function is a <a class="reference internal" href="../glossary.html#term-decorator"><span class="xref std std-term">decorator</span></a> that can be used to define a factory
  276. function for <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 asynchronous context managers,
  277. without needing to create a class or separate <a class="reference internal" href="../reference/datamodel.html#object.__aenter__" title="object.__aenter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__aenter__()</span></code></a> and
  278. <a class="reference internal" href="../reference/datamodel.html#object.__aexit__" title="object.__aexit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__aexit__()</span></code></a> methods. It must be applied to an <a class="reference internal" href="../glossary.html#term-asynchronous-generator"><span class="xref std std-term">asynchronous
  279. generator</span></a> function.</p>
  280. <p>A simple example:</p>
  281. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">contextlib</span> <span class="kn">import</span> <span class="n">asynccontextmanager</span>
  282. <span class="nd">@asynccontextmanager</span>
  283. <span class="k">async</span> <span class="k">def</span> <span class="nf">get_connection</span><span class="p">():</span>
  284. <span class="n">conn</span> <span class="o">=</span> <span class="k">await</span> <span class="n">acquire_db_connection</span><span class="p">()</span>
  285. <span class="k">try</span><span class="p">:</span>
  286. <span class="k">yield</span> <span class="n">conn</span>
  287. <span class="k">finally</span><span class="p">:</span>
  288. <span class="k">await</span> <span class="n">release_db_connection</span><span class="p">(</span><span class="n">conn</span><span class="p">)</span>
  289. <span class="k">async</span> <span class="k">def</span> <span class="nf">get_all_users</span><span class="p">():</span>
  290. <span class="k">async</span> <span class="k">with</span> <span class="n">get_connection</span><span class="p">()</span> <span class="k">as</span> <span class="n">conn</span><span class="p">:</span>
  291. <span class="k">return</span> <span class="n">conn</span><span class="o">.</span><span class="n">query</span><span class="p">(</span><span class="s1">&#39;SELECT ...&#39;</span><span class="p">)</span>
  292. </pre></div>
  293. </div>
  294. <div class="versionadded">
  295. <p><span class="versionmodified added">New in version 3.7.</span></p>
  296. </div>
  297. <p>Context managers defined with <a class="reference internal" href="#contextlib.asynccontextmanager" title="contextlib.asynccontextmanager"><code class="xref py py-func docutils literal notranslate"><span class="pre">asynccontextmanager()</span></code></a> can be used
  298. either as decorators or with <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> statements:</p>
  299. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">time</span>
  300. <span class="kn">from</span> <span class="nn">contextlib</span> <span class="kn">import</span> <span class="n">asynccontextmanager</span>
  301. <span class="nd">@asynccontextmanager</span>
  302. <span class="k">async</span> <span class="k">def</span> <span class="nf">timeit</span><span class="p">():</span>
  303. <span class="n">now</span> <span class="o">=</span> <span class="n">time</span><span class="o">.</span><span class="n">monotonic</span><span class="p">()</span>
  304. <span class="k">try</span><span class="p">:</span>
  305. <span class="k">yield</span>
  306. <span class="k">finally</span><span class="p">:</span>
  307. <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;it took </span><span class="si">{</span><span class="n">time</span><span class="o">.</span><span class="n">monotonic</span><span class="p">()</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="n">now</span><span class="si">}</span><span class="s1">s to run&#39;</span><span class="p">)</span>
  308. <span class="nd">@timeit</span><span class="p">()</span>
  309. <span class="k">async</span> <span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
  310. <span class="c1"># ... async code ...</span>
  311. </pre></div>
  312. </div>
  313. <p>When used as a decorator, a new generator instance is implicitly created on
  314. each function call. This allows the otherwise “one-shot” context managers
  315. created by <a class="reference internal" href="#contextlib.asynccontextmanager" title="contextlib.asynccontextmanager"><code class="xref py py-func docutils literal notranslate"><span class="pre">asynccontextmanager()</span></code></a> to meet the requirement that context
  316. managers support multiple invocations in order to be used as decorators.</p>
  317. </div></blockquote>
  318. <div class="versionchanged">
  319. <p><span class="versionmodified changed">Changed in version 3.10: </span>Async context managers created with <a class="reference internal" href="#contextlib.asynccontextmanager" title="contextlib.asynccontextmanager"><code class="xref py py-func docutils literal notranslate"><span class="pre">asynccontextmanager()</span></code></a> can
  320. be used as decorators.</p>
  321. </div>
  322. </dd></dl>
  323. <dl class="py function">
  324. <dt class="sig sig-object py" id="contextlib.closing">
  325. <span class="sig-prename descclassname"><span class="pre">contextlib.</span></span><span class="sig-name descname"><span class="pre">closing</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">thing</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#contextlib.closing" title="Link to this definition">¶</a></dt>
  326. <dd><p>Return a context manager that closes <em>thing</em> upon completion of the block. This
  327. is basically equivalent to:</p>
  328. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">contextlib</span> <span class="kn">import</span> <span class="n">contextmanager</span>
  329. <span class="nd">@contextmanager</span>
  330. <span class="k">def</span> <span class="nf">closing</span><span class="p">(</span><span class="n">thing</span><span class="p">):</span>
  331. <span class="k">try</span><span class="p">:</span>
  332. <span class="k">yield</span> <span class="n">thing</span>
  333. <span class="k">finally</span><span class="p">:</span>
  334. <span class="n">thing</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
  335. </pre></div>
  336. </div>
  337. <p>And lets you write code like this:</p>
  338. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">contextlib</span> <span class="kn">import</span> <span class="n">closing</span>
  339. <span class="kn">from</span> <span class="nn">urllib.request</span> <span class="kn">import</span> <span class="n">urlopen</span>
  340. <span class="k">with</span> <span class="n">closing</span><span class="p">(</span><span class="n">urlopen</span><span class="p">(</span><span class="s1">&#39;https://www.python.org&#39;</span><span class="p">))</span> <span class="k">as</span> <span class="n">page</span><span class="p">:</span>
  341. <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">page</span><span class="p">:</span>
  342. <span class="nb">print</span><span class="p">(</span><span class="n">line</span><span class="p">)</span>
  343. </pre></div>
  344. </div>
  345. <p>without needing to explicitly close <code class="docutils literal notranslate"><span class="pre">page</span></code>. Even if an error occurs,
  346. <code class="docutils literal notranslate"><span class="pre">page.close()</span></code> will be called when 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> block is exited.</p>
  347. <div class="admonition note">
  348. <p class="admonition-title">Note</p>
  349. <p>Most types managing resources support the <a class="reference internal" href="../glossary.html#term-context-manager"><span class="xref std std-term">context manager</span></a> protocol,
  350. which closes <em>thing</em> on leaving 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.
  351. As such, <code class="xref py py-func docutils literal notranslate"><span class="pre">closing()</span></code> is most useful for third party types that don’t
  352. support context managers.
  353. This example is purely for illustration purposes,
  354. as <a class="reference internal" href="urllib.request.html#urllib.request.urlopen" title="urllib.request.urlopen"><code class="xref py py-func docutils literal notranslate"><span class="pre">urlopen()</span></code></a> would normally be used in a context manager.</p>
  355. </div>
  356. </dd></dl>
  357. <dl class="py function">
  358. <dt class="sig sig-object py" id="contextlib.aclosing">
  359. <span class="sig-prename descclassname"><span class="pre">contextlib.</span></span><span class="sig-name descname"><span class="pre">aclosing</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">thing</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#contextlib.aclosing" title="Link to this definition">¶</a></dt>
  360. <dd><p>Return an async context manager that calls the <code class="docutils literal notranslate"><span class="pre">aclose()</span></code> method of <em>thing</em>
  361. upon completion of the block. This is basically equivalent to:</p>
  362. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">contextlib</span> <span class="kn">import</span> <span class="n">asynccontextmanager</span>
  363. <span class="nd">@asynccontextmanager</span>
  364. <span class="k">async</span> <span class="k">def</span> <span class="nf">aclosing</span><span class="p">(</span><span class="n">thing</span><span class="p">):</span>
  365. <span class="k">try</span><span class="p">:</span>
  366. <span class="k">yield</span> <span class="n">thing</span>
  367. <span class="k">finally</span><span class="p">:</span>
  368. <span class="k">await</span> <span class="n">thing</span><span class="o">.</span><span class="n">aclose</span><span class="p">()</span>
  369. </pre></div>
  370. </div>
  371. <p>Significantly, <code class="docutils literal notranslate"><span class="pre">aclosing()</span></code> supports deterministic cleanup of async
  372. generators when they happen to exit early by <a class="reference internal" href="../reference/simple_stmts.html#break"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code></a> or an
  373. exception. For example:</p>
  374. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">contextlib</span> <span class="kn">import</span> <span class="n">aclosing</span>
  375. <span class="k">async</span> <span class="k">with</span> <span class="n">aclosing</span><span class="p">(</span><span class="n">my_generator</span><span class="p">())</span> <span class="k">as</span> <span class="n">values</span><span class="p">:</span>
  376. <span class="k">async</span> <span class="k">for</span> <span class="n">value</span> <span class="ow">in</span> <span class="n">values</span><span class="p">:</span>
  377. <span class="k">if</span> <span class="n">value</span> <span class="o">==</span> <span class="mi">42</span><span class="p">:</span>
  378. <span class="k">break</span>
  379. </pre></div>
  380. </div>
  381. <p>This pattern ensures that the generator’s async exit code is executed in
  382. the same context as its iterations (so that exceptions and context
  383. variables work as expected, and the exit code isn’t run after the
  384. lifetime of some task it depends on).</p>
  385. <div class="versionadded">
  386. <p><span class="versionmodified added">New in version 3.10.</span></p>
  387. </div>
  388. </dd></dl>
  389. <dl class="py function" id="simplifying-support-for-single-optional-context-managers">
  390. <dt class="sig sig-object py" id="contextlib.nullcontext">
  391. <span class="sig-prename descclassname"><span class="pre">contextlib.</span></span><span class="sig-name descname"><span class="pre">nullcontext</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">enter_result</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#contextlib.nullcontext" title="Link to this definition">¶</a></dt>
  392. <dd><p>Return a context manager that returns <em>enter_result</em> from <code class="docutils literal notranslate"><span class="pre">__enter__</span></code>, but
  393. otherwise does nothing. It is intended to be used as a stand-in for an
  394. optional context manager, for example:</p>
  395. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">myfunction</span><span class="p">(</span><span class="n">arg</span><span class="p">,</span> <span class="n">ignore_exceptions</span><span class="o">=</span><span class="kc">False</span><span class="p">):</span>
  396. <span class="k">if</span> <span class="n">ignore_exceptions</span><span class="p">:</span>
  397. <span class="c1"># Use suppress to ignore all exceptions.</span>
  398. <span class="n">cm</span> <span class="o">=</span> <span class="n">contextlib</span><span class="o">.</span><span class="n">suppress</span><span class="p">(</span><span class="ne">Exception</span><span class="p">)</span>
  399. <span class="k">else</span><span class="p">:</span>
  400. <span class="c1"># Do not ignore any exceptions, cm has no effect.</span>
  401. <span class="n">cm</span> <span class="o">=</span> <span class="n">contextlib</span><span class="o">.</span><span class="n">nullcontext</span><span class="p">()</span>
  402. <span class="k">with</span> <span class="n">cm</span><span class="p">:</span>
  403. <span class="c1"># Do something</span>
  404. </pre></div>
  405. </div>
  406. <p>An example using <em>enter_result</em>:</p>
  407. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">process_file</span><span class="p">(</span><span class="n">file_or_path</span><span class="p">):</span>
  408. <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">file_or_path</span><span class="p">,</span> <span class="nb">str</span><span class="p">):</span>
  409. <span class="c1"># If string, open file</span>
  410. <span class="n">cm</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">file_or_path</span><span class="p">)</span>
  411. <span class="k">else</span><span class="p">:</span>
  412. <span class="c1"># Caller is responsible for closing file</span>
  413. <span class="n">cm</span> <span class="o">=</span> <span class="n">nullcontext</span><span class="p">(</span><span class="n">file_or_path</span><span class="p">)</span>
  414. <span class="k">with</span> <span class="n">cm</span> <span class="k">as</span> <span class="n">file</span><span class="p">:</span>
  415. <span class="c1"># Perform processing on the file</span>
  416. </pre></div>
  417. </div>
  418. <p>It can also be used as a stand-in for
  419. <a class="reference internal" href="../reference/datamodel.html#async-context-managers"><span class="std std-ref">asynchronous context managers</span></a>:</p>
  420. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">async</span> <span class="k">def</span> <span class="nf">send_http</span><span class="p">(</span><span class="n">session</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
  421. <span class="k">if</span> <span class="ow">not</span> <span class="n">session</span><span class="p">:</span>
  422. <span class="c1"># If no http session, create it with aiohttp</span>
  423. <span class="n">cm</span> <span class="o">=</span> <span class="n">aiohttp</span><span class="o">.</span><span class="n">ClientSession</span><span class="p">()</span>
  424. <span class="k">else</span><span class="p">:</span>
  425. <span class="c1"># Caller is responsible for closing the session</span>
  426. <span class="n">cm</span> <span class="o">=</span> <span class="n">nullcontext</span><span class="p">(</span><span class="n">session</span><span class="p">)</span>
  427. <span class="k">async</span> <span class="k">with</span> <span class="n">cm</span> <span class="k">as</span> <span class="n">session</span><span class="p">:</span>
  428. <span class="c1"># Send http requests with session</span>
  429. </pre></div>
  430. </div>
  431. <div class="versionadded">
  432. <p><span class="versionmodified added">New in version 3.7.</span></p>
  433. </div>
  434. <div class="versionchanged">
  435. <p><span class="versionmodified changed">Changed in version 3.10: </span><a class="reference internal" href="../glossary.html#term-asynchronous-context-manager"><span class="xref std std-term">asynchronous context manager</span></a> support was added.</p>
  436. </div>
  437. </dd></dl>
  438. <dl class="py function">
  439. <dt class="sig sig-object py" id="contextlib.suppress">
  440. <span class="sig-prename descclassname"><span class="pre">contextlib.</span></span><span class="sig-name descname"><span class="pre">suppress</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="o"><span class="pre">*</span></span><span class="n"><span class="pre">exceptions</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#contextlib.suppress" title="Link to this definition">¶</a></dt>
  441. <dd><p>Return a context manager that suppresses any of the specified exceptions
  442. if they occur in the body of a <code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code> statement and then
  443. resumes execution with the first statement following the end of the
  444. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code> statement.</p>
  445. <p>As with any other mechanism that completely suppresses exceptions, this
  446. context manager should be used only to cover very specific errors where
  447. silently continuing with program execution is known to be the right
  448. thing to do.</p>
  449. <p>For example:</p>
  450. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">contextlib</span> <span class="kn">import</span> <span class="n">suppress</span>
  451. <span class="k">with</span> <span class="n">suppress</span><span class="p">(</span><span class="ne">FileNotFoundError</span><span class="p">):</span>
  452. <span class="n">os</span><span class="o">.</span><span class="n">remove</span><span class="p">(</span><span class="s1">&#39;somefile.tmp&#39;</span><span class="p">)</span>
  453. <span class="k">with</span> <span class="n">suppress</span><span class="p">(</span><span class="ne">FileNotFoundError</span><span class="p">):</span>
  454. <span class="n">os</span><span class="o">.</span><span class="n">remove</span><span class="p">(</span><span class="s1">&#39;someotherfile.tmp&#39;</span><span class="p">)</span>
  455. </pre></div>
  456. </div>
  457. <p>This code is equivalent to:</p>
  458. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span>
  459. <span class="n">os</span><span class="o">.</span><span class="n">remove</span><span class="p">(</span><span class="s1">&#39;somefile.tmp&#39;</span><span class="p">)</span>
  460. <span class="k">except</span> <span class="ne">FileNotFoundError</span><span class="p">:</span>
  461. <span class="k">pass</span>
  462. <span class="k">try</span><span class="p">:</span>
  463. <span class="n">os</span><span class="o">.</span><span class="n">remove</span><span class="p">(</span><span class="s1">&#39;someotherfile.tmp&#39;</span><span class="p">)</span>
  464. <span class="k">except</span> <span class="ne">FileNotFoundError</span><span class="p">:</span>
  465. <span class="k">pass</span>
  466. </pre></div>
  467. </div>
  468. <p>This context manager is <a class="reference internal" href="#reentrant-cms"><span class="std std-ref">reentrant</span></a>.</p>
  469. <p>If the code within the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code> block raises a
  470. <a class="reference internal" href="exceptions.html#BaseExceptionGroup" title="BaseExceptionGroup"><code class="xref py py-exc docutils literal notranslate"><span class="pre">BaseExceptionGroup</span></code></a>, suppressed exceptions are removed from the
  471. group. If any exceptions in the group are not suppressed, a group containing them is re-raised.</p>
  472. <div class="versionadded">
  473. <p><span class="versionmodified added">New in version 3.4.</span></p>
  474. </div>
  475. <div class="versionchanged">
  476. <p><span class="versionmodified changed">Changed in version 3.12: </span><code class="docutils literal notranslate"><span class="pre">suppress</span></code> now supports suppressing exceptions raised as
  477. part of an <a class="reference internal" href="exceptions.html#BaseExceptionGroup" title="BaseExceptionGroup"><code class="xref py py-exc docutils literal notranslate"><span class="pre">BaseExceptionGroup</span></code></a>.</p>
  478. </div>
  479. </dd></dl>
  480. <dl class="py function">
  481. <dt class="sig sig-object py" id="contextlib.redirect_stdout">
  482. <span class="sig-prename descclassname"><span class="pre">contextlib.</span></span><span class="sig-name descname"><span class="pre">redirect_stdout</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">new_target</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#contextlib.redirect_stdout" title="Link to this definition">¶</a></dt>
  483. <dd><p>Context manager for temporarily redirecting <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> to
  484. another file or file-like object.</p>
  485. <p>This tool adds flexibility to existing functions or classes whose output
  486. is hardwired to stdout.</p>
  487. <p>For example, the output of <a class="reference internal" href="functions.html#help" title="help"><code class="xref py py-func docutils literal notranslate"><span class="pre">help()</span></code></a> normally is sent to <em>sys.stdout</em>.
  488. You can capture that output in a string by redirecting the output to an
  489. <a class="reference internal" href="io.html#io.StringIO" title="io.StringIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">io.StringIO</span></code></a> object. The replacement stream is returned from the
  490. <code class="docutils literal notranslate"><span class="pre">__enter__</span></code> method and so is available as the target of the
  491. <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:</p>
  492. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="n">redirect_stdout</span><span class="p">(</span><span class="n">io</span><span class="o">.</span><span class="n">StringIO</span><span class="p">())</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
  493. <span class="n">help</span><span class="p">(</span><span class="nb">pow</span><span class="p">)</span>
  494. <span class="n">s</span> <span class="o">=</span> <span class="n">f</span><span class="o">.</span><span class="n">getvalue</span><span class="p">()</span>
  495. </pre></div>
  496. </div>
  497. <p>To send the output of <a class="reference internal" href="functions.html#help" title="help"><code class="xref py py-func docutils literal notranslate"><span class="pre">help()</span></code></a> to a file on disk, redirect the output
  498. to a regular file:</p>
  499. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;help.txt&#39;</span><span class="p">,</span> <span class="s1">&#39;w&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
  500. <span class="k">with</span> <span class="n">redirect_stdout</span><span class="p">(</span><span class="n">f</span><span class="p">):</span>
  501. <span class="n">help</span><span class="p">(</span><span class="nb">pow</span><span class="p">)</span>
  502. </pre></div>
  503. </div>
  504. <p>To send the output of <a class="reference internal" href="functions.html#help" title="help"><code class="xref py py-func docutils literal notranslate"><span class="pre">help()</span></code></a> to <em>sys.stderr</em>:</p>
  505. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="n">redirect_stdout</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">stderr</span><span class="p">):</span>
  506. <span class="n">help</span><span class="p">(</span><span class="nb">pow</span><span class="p">)</span>
  507. </pre></div>
  508. </div>
  509. <p>Note that the global side effect on <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> means that this
  510. context manager is not suitable for use in library code and most threaded
  511. applications. It also has no effect on the output of subprocesses.
  512. However, it is still a useful approach for many utility scripts.</p>
  513. <p>This context manager is <a class="reference internal" href="#reentrant-cms"><span class="std std-ref">reentrant</span></a>.</p>
  514. <div class="versionadded">
  515. <p><span class="versionmodified added">New in version 3.4.</span></p>
  516. </div>
  517. </dd></dl>
  518. <dl class="py function">
  519. <dt class="sig sig-object py" id="contextlib.redirect_stderr">
  520. <span class="sig-prename descclassname"><span class="pre">contextlib.</span></span><span class="sig-name descname"><span class="pre">redirect_stderr</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">new_target</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#contextlib.redirect_stderr" title="Link to this definition">¶</a></dt>
  521. <dd><p>Similar to <a class="reference internal" href="#contextlib.redirect_stdout" title="contextlib.redirect_stdout"><code class="xref py py-func docutils literal notranslate"><span class="pre">redirect_stdout()</span></code></a> but redirecting
  522. <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> to another file or file-like object.</p>
  523. <p>This context manager is <a class="reference internal" href="#reentrant-cms"><span class="std std-ref">reentrant</span></a>.</p>
  524. <div class="versionadded">
  525. <p><span class="versionmodified added">New in version 3.5.</span></p>
  526. </div>
  527. </dd></dl>
  528. <dl class="py function">
  529. <dt class="sig sig-object py" id="contextlib.chdir">
  530. <span class="sig-prename descclassname"><span class="pre">contextlib.</span></span><span class="sig-name descname"><span class="pre">chdir</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">path</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#contextlib.chdir" title="Link to this definition">¶</a></dt>
  531. <dd><p>Non parallel-safe context manager to change the current working directory.
  532. As this changes a global state, the working directory, it is not suitable
  533. for use in most threaded or async contexts. It is also not suitable for most
  534. non-linear code execution, like generators, where the program execution is
  535. temporarily relinquished – unless explicitly desired, you should not yield
  536. when this context manager is active.</p>
  537. <p>This is a simple wrapper around <a class="reference internal" href="os.html#os.chdir" title="os.chdir"><code class="xref py py-func docutils literal notranslate"><span class="pre">chdir()</span></code></a>, it changes the current
  538. working directory upon entering and restores the old one on exit.</p>
  539. <p>This context manager is <a class="reference internal" href="#reentrant-cms"><span class="std std-ref">reentrant</span></a>.</p>
  540. <div class="versionadded">
  541. <p><span class="versionmodified added">New in version 3.11.</span></p>
  542. </div>
  543. </dd></dl>
  544. <dl class="py class">
  545. <dt class="sig sig-object py" id="contextlib.ContextDecorator">
  546. <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">contextlib.</span></span><span class="sig-name descname"><span class="pre">ContextDecorator</span></span><a class="headerlink" href="#contextlib.ContextDecorator" title="Link to this definition">¶</a></dt>
  547. <dd><p>A base class that enables a context manager to also be used as a decorator.</p>
  548. <p>Context managers inheriting from <code class="docutils literal notranslate"><span class="pre">ContextDecorator</span></code> have to implement
  549. <code class="docutils literal notranslate"><span class="pre">__enter__</span></code> and <code class="docutils literal notranslate"><span class="pre">__exit__</span></code> as normal. <code class="docutils literal notranslate"><span class="pre">__exit__</span></code> retains its optional
  550. exception handling even when used as a decorator.</p>
  551. <p><code class="docutils literal notranslate"><span class="pre">ContextDecorator</span></code> is used by <a class="reference internal" href="#contextlib.contextmanager" title="contextlib.contextmanager"><code class="xref py py-func docutils literal notranslate"><span class="pre">contextmanager()</span></code></a>, so you get this
  552. functionality automatically.</p>
  553. <p>Example of <code class="docutils literal notranslate"><span class="pre">ContextDecorator</span></code>:</p>
  554. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">contextlib</span> <span class="kn">import</span> <span class="n">ContextDecorator</span>
  555. <span class="k">class</span> <span class="nc">mycontext</span><span class="p">(</span><span class="n">ContextDecorator</span><span class="p">):</span>
  556. <span class="k">def</span> <span class="fm">__enter__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  557. <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;Starting&#39;</span><span class="p">)</span>
  558. <span class="k">return</span> <span class="bp">self</span>
  559. <span class="k">def</span> <span class="fm">__exit__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">exc</span><span class="p">):</span>
  560. <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;Finishing&#39;</span><span class="p">)</span>
  561. <span class="k">return</span> <span class="kc">False</span>
  562. </pre></div>
  563. </div>
  564. <p>The class can then be used like this:</p>
  565. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nd">@mycontext</span><span class="p">()</span>
  566. <span class="gp">... </span><span class="k">def</span> <span class="nf">function</span><span class="p">():</span>
  567. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;The bit in the middle&#39;</span><span class="p">)</span>
  568. <span class="gp">...</span>
  569. <span class="gp">&gt;&gt;&gt; </span><span class="n">function</span><span class="p">()</span>
  570. <span class="go">Starting</span>
  571. <span class="go">The bit in the middle</span>
  572. <span class="go">Finishing</span>
  573. <span class="gp">&gt;&gt;&gt; </span><span class="k">with</span> <span class="n">mycontext</span><span class="p">():</span>
  574. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;The bit in the middle&#39;</span><span class="p">)</span>
  575. <span class="gp">...</span>
  576. <span class="go">Starting</span>
  577. <span class="go">The bit in the middle</span>
  578. <span class="go">Finishing</span>
  579. </pre></div>
  580. </div>
  581. <p>This change is just syntactic sugar for any construct of the following form:</p>
  582. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">f</span><span class="p">():</span>
  583. <span class="k">with</span> <span class="n">cm</span><span class="p">():</span>
  584. <span class="c1"># Do stuff</span>
  585. </pre></div>
  586. </div>
  587. <p><code class="docutils literal notranslate"><span class="pre">ContextDecorator</span></code> lets you instead write:</p>
  588. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="nd">@cm</span><span class="p">()</span>
  589. <span class="k">def</span> <span class="nf">f</span><span class="p">():</span>
  590. <span class="c1"># Do stuff</span>
  591. </pre></div>
  592. </div>
  593. <p>It makes it clear that the <code class="docutils literal notranslate"><span class="pre">cm</span></code> applies to the whole function, rather than
  594. just a piece of it (and saving an indentation level is nice, too).</p>
  595. <p>Existing context managers that already have a base class can be extended by
  596. using <code class="docutils literal notranslate"><span class="pre">ContextDecorator</span></code> as a mixin class:</p>
  597. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">contextlib</span> <span class="kn">import</span> <span class="n">ContextDecorator</span>
  598. <span class="k">class</span> <span class="nc">mycontext</span><span class="p">(</span><span class="n">ContextBaseClass</span><span class="p">,</span> <span class="n">ContextDecorator</span><span class="p">):</span>
  599. <span class="k">def</span> <span class="fm">__enter__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  600. <span class="k">return</span> <span class="bp">self</span>
  601. <span class="k">def</span> <span class="fm">__exit__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">exc</span><span class="p">):</span>
  602. <span class="k">return</span> <span class="kc">False</span>
  603. </pre></div>
  604. </div>
  605. <div class="admonition note">
  606. <p class="admonition-title">Note</p>
  607. <p>As the decorated function must be able to be called multiple times, the
  608. underlying context manager must support use in multiple <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>
  609. statements. If this is not the case, then the original construct with the
  610. explicit <code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code> statement inside the function should be used.</p>
  611. </div>
  612. <div class="versionadded">
  613. <p><span class="versionmodified added">New in version 3.2.</span></p>
  614. </div>
  615. </dd></dl>
  616. <dl class="py class">
  617. <dt class="sig sig-object py" id="contextlib.AsyncContextDecorator">
  618. <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">contextlib.</span></span><span class="sig-name descname"><span class="pre">AsyncContextDecorator</span></span><a class="headerlink" href="#contextlib.AsyncContextDecorator" title="Link to this definition">¶</a></dt>
  619. <dd><p>Similar to <a class="reference internal" href="#contextlib.ContextDecorator" title="contextlib.ContextDecorator"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContextDecorator</span></code></a> but only for asynchronous functions.</p>
  620. <p>Example of <code class="docutils literal notranslate"><span class="pre">AsyncContextDecorator</span></code>:</p>
  621. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">asyncio</span> <span class="kn">import</span> <span class="n">run</span>
  622. <span class="kn">from</span> <span class="nn">contextlib</span> <span class="kn">import</span> <span class="n">AsyncContextDecorator</span>
  623. <span class="k">class</span> <span class="nc">mycontext</span><span class="p">(</span><span class="n">AsyncContextDecorator</span><span class="p">):</span>
  624. <span class="k">async</span> <span class="k">def</span> <span class="fm">__aenter__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  625. <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;Starting&#39;</span><span class="p">)</span>
  626. <span class="k">return</span> <span class="bp">self</span>
  627. <span class="k">async</span> <span class="k">def</span> <span class="fm">__aexit__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">exc</span><span class="p">):</span>
  628. <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;Finishing&#39;</span><span class="p">)</span>
  629. <span class="k">return</span> <span class="kc">False</span>
  630. </pre></div>
  631. </div>
  632. <p>The class can then be used like this:</p>
  633. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nd">@mycontext</span><span class="p">()</span>
  634. <span class="gp">... </span><span class="k">async</span> <span class="k">def</span> <span class="nf">function</span><span class="p">():</span>
  635. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;The bit in the middle&#39;</span><span class="p">)</span>
  636. <span class="gp">...</span>
  637. <span class="gp">&gt;&gt;&gt; </span><span class="n">run</span><span class="p">(</span><span class="n">function</span><span class="p">())</span>
  638. <span class="go">Starting</span>
  639. <span class="go">The bit in the middle</span>
  640. <span class="go">Finishing</span>
  641. <span class="gp">&gt;&gt;&gt; </span><span class="k">async</span> <span class="k">def</span> <span class="nf">function</span><span class="p">():</span>
  642. <span class="gp">... </span> <span class="k">async</span> <span class="k">with</span> <span class="n">mycontext</span><span class="p">():</span>
  643. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;The bit in the middle&#39;</span><span class="p">)</span>
  644. <span class="gp">...</span>
  645. <span class="gp">&gt;&gt;&gt; </span><span class="n">run</span><span class="p">(</span><span class="n">function</span><span class="p">())</span>
  646. <span class="go">Starting</span>
  647. <span class="go">The bit in the middle</span>
  648. <span class="go">Finishing</span>
  649. </pre></div>
  650. </div>
  651. <div class="versionadded">
  652. <p><span class="versionmodified added">New in version 3.10.</span></p>
  653. </div>
  654. </dd></dl>
  655. <dl class="py class">
  656. <dt class="sig sig-object py" id="contextlib.ExitStack">
  657. <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">contextlib.</span></span><span class="sig-name descname"><span class="pre">ExitStack</span></span><a class="headerlink" href="#contextlib.ExitStack" title="Link to this definition">¶</a></dt>
  658. <dd><p>A context manager that is designed to make it easy to programmatically
  659. combine other context managers and cleanup functions, especially those
  660. that are optional or otherwise driven by input data.</p>
  661. <p>For example, a set of files may easily be handled in a single with
  662. statement as follows:</p>
  663. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="n">ExitStack</span><span class="p">()</span> <span class="k">as</span> <span class="n">stack</span><span class="p">:</span>
  664. <span class="n">files</span> <span class="o">=</span> <span class="p">[</span><span class="n">stack</span><span class="o">.</span><span class="n">enter_context</span><span class="p">(</span><span class="nb">open</span><span class="p">(</span><span class="n">fname</span><span class="p">))</span> <span class="k">for</span> <span class="n">fname</span> <span class="ow">in</span> <span class="n">filenames</span><span class="p">]</span>
  665. <span class="c1"># All opened files will automatically be closed at the end of</span>
  666. <span class="c1"># the with statement, even if attempts to open files later</span>
  667. <span class="c1"># in the list raise an exception</span>
  668. </pre></div>
  669. </div>
  670. <p>The <a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> method returns the <a class="reference internal" href="#contextlib.ExitStack" title="contextlib.ExitStack"><code class="xref py py-class docutils literal notranslate"><span class="pre">ExitStack</span></code></a> instance, and
  671. performs no additional operations.</p>
  672. <p>Each instance maintains a stack of registered callbacks that are called in
  673. reverse order when the instance is closed (either explicitly or implicitly
  674. at the end of a <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). Note that callbacks are <em>not</em>
  675. invoked implicitly when the context stack instance is garbage collected.</p>
  676. <p>This stack model is used so that context managers that acquire their
  677. resources in their <code class="docutils literal notranslate"><span class="pre">__init__</span></code> method (such as file objects) can be
  678. handled correctly.</p>
  679. <p>Since registered callbacks are invoked in the reverse order of
  680. registration, this ends up behaving as if multiple nested <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>
  681. statements had been used with the registered set of callbacks. This even
  682. extends to exception handling - if an inner callback suppresses or replaces
  683. an exception, then outer callbacks will be passed arguments based on that
  684. updated state.</p>
  685. <p>This is a relatively low level API that takes care of the details of
  686. correctly unwinding the stack of exit callbacks. It provides a suitable
  687. foundation for higher level context managers that manipulate the exit
  688. stack in application specific ways.</p>
  689. <div class="versionadded">
  690. <p><span class="versionmodified added">New in version 3.3.</span></p>
  691. </div>
  692. <dl class="py method">
  693. <dt class="sig sig-object py" id="contextlib.ExitStack.enter_context">
  694. <span class="sig-name descname"><span class="pre">enter_context</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">cm</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#contextlib.ExitStack.enter_context" title="Link to this definition">¶</a></dt>
  695. <dd><p>Enters a new context manager and adds its <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> method to
  696. the callback stack. The return value is the result of the context
  697. manager’s own <a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> method.</p>
  698. <p>These context managers may suppress exceptions just as they normally
  699. would if used directly as part of a <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.</p>
  700. <div class="versionchanged">
  701. <p><span class="versionmodified changed">Changed in version 3.11: </span>Raises <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> instead of <a class="reference internal" href="exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a> if <em>cm</em>
  702. is not a context manager.</p>
  703. </div>
  704. </dd></dl>
  705. <dl class="py method">
  706. <dt class="sig sig-object py" id="contextlib.ExitStack.push">
  707. <span class="sig-name descname"><span class="pre">push</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">exit</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#contextlib.ExitStack.push" title="Link to this definition">¶</a></dt>
  708. <dd><p>Adds a context manager’s <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> method to the callback stack.</p>
  709. <p>As <code class="docutils literal notranslate"><span class="pre">__enter__</span></code> is <em>not</em> invoked, this method can be used to cover
  710. part of an <a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> implementation with a context manager’s own
  711. <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> method.</p>
  712. <p>If passed an object that is not a context manager, this method assumes
  713. it is a callback with the same signature as a context manager’s
  714. <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> method and adds it directly to the callback stack.</p>
  715. <p>By returning true values, these callbacks can suppress exceptions the
  716. same way context manager <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> methods can.</p>
  717. <p>The passed in object is returned from the function, allowing this
  718. method to be used as a function decorator.</p>
  719. </dd></dl>
  720. <dl class="py method">
  721. <dt class="sig sig-object py" id="contextlib.ExitStack.callback">
  722. <span class="sig-name descname"><span class="pre">callback</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">callback</span></span></em>, <em class="sig-param"><span class="o"><span class="pre">/</span></span></em>, <em class="sig-param"><span class="o"><span class="pre">*</span></span><span class="n"><span class="pre">args</span></span></em>, <em class="sig-param"><span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">kwds</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#contextlib.ExitStack.callback" title="Link to this definition">¶</a></dt>
  723. <dd><p>Accepts an arbitrary callback function and arguments and adds it to
  724. the callback stack.</p>
  725. <p>Unlike the other methods, callbacks added this way cannot suppress
  726. exceptions (as they are never passed the exception details).</p>
  727. <p>The passed in callback is returned from the function, allowing this
  728. method to be used as a function decorator.</p>
  729. </dd></dl>
  730. <dl class="py method">
  731. <dt class="sig sig-object py" id="contextlib.ExitStack.pop_all">
  732. <span class="sig-name descname"><span class="pre">pop_all</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#contextlib.ExitStack.pop_all" title="Link to this definition">¶</a></dt>
  733. <dd><p>Transfers the callback stack to a fresh <a class="reference internal" href="#contextlib.ExitStack" title="contextlib.ExitStack"><code class="xref py py-class docutils literal notranslate"><span class="pre">ExitStack</span></code></a> instance
  734. and returns it. No callbacks are invoked by this operation - instead,
  735. they will now be invoked when the new stack is closed (either
  736. explicitly or implicitly at the end of a <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).</p>
  737. <p>For example, a group of files can be opened as an “all or nothing”
  738. operation as follows:</p>
  739. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="n">ExitStack</span><span class="p">()</span> <span class="k">as</span> <span class="n">stack</span><span class="p">:</span>
  740. <span class="n">files</span> <span class="o">=</span> <span class="p">[</span><span class="n">stack</span><span class="o">.</span><span class="n">enter_context</span><span class="p">(</span><span class="nb">open</span><span class="p">(</span><span class="n">fname</span><span class="p">))</span> <span class="k">for</span> <span class="n">fname</span> <span class="ow">in</span> <span class="n">filenames</span><span class="p">]</span>
  741. <span class="c1"># Hold onto the close method, but don&#39;t call it yet.</span>
  742. <span class="n">close_files</span> <span class="o">=</span> <span class="n">stack</span><span class="o">.</span><span class="n">pop_all</span><span class="p">()</span><span class="o">.</span><span class="n">close</span>
  743. <span class="c1"># If opening any file fails, all previously opened files will be</span>
  744. <span class="c1"># closed automatically. If all files are opened successfully,</span>
  745. <span class="c1"># they will remain open even after the with statement ends.</span>
  746. <span class="c1"># close_files() can then be invoked explicitly to close them all.</span>
  747. </pre></div>
  748. </div>
  749. </dd></dl>
  750. <dl class="py method">
  751. <dt class="sig sig-object py" id="contextlib.ExitStack.close">
  752. <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="#contextlib.ExitStack.close" title="Link to this definition">¶</a></dt>
  753. <dd><p>Immediately unwinds the callback stack, invoking callbacks in the
  754. reverse order of registration. For any context managers and exit
  755. callbacks registered, the arguments passed in will indicate that no
  756. exception occurred.</p>
  757. </dd></dl>
  758. </dd></dl>
  759. <dl class="py class">
  760. <dt class="sig sig-object py" id="contextlib.AsyncExitStack">
  761. <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">contextlib.</span></span><span class="sig-name descname"><span class="pre">AsyncExitStack</span></span><a class="headerlink" href="#contextlib.AsyncExitStack" title="Link to this definition">¶</a></dt>
  762. <dd><p>An <a class="reference internal" href="../reference/datamodel.html#async-context-managers"><span class="std std-ref">asynchronous context manager</span></a>, similar
  763. to <a class="reference internal" href="#contextlib.ExitStack" title="contextlib.ExitStack"><code class="xref py py-class docutils literal notranslate"><span class="pre">ExitStack</span></code></a>, that supports combining both synchronous and
  764. asynchronous context managers, as well as having coroutines for
  765. cleanup logic.</p>
  766. <p>The <a class="reference internal" href="#contextlib.ExitStack.close" title="contextlib.ExitStack.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a> method is not implemented; <a class="reference internal" href="#contextlib.AsyncExitStack.aclose" title="contextlib.AsyncExitStack.aclose"><code class="xref py py-meth docutils literal notranslate"><span class="pre">aclose()</span></code></a> must be used
  767. instead.</p>
  768. <dl class="py method">
  769. <dt class="sig sig-object py" id="contextlib.AsyncExitStack.enter_async_context">
  770. <em class="property"><span class="pre">coroutine</span> </em><span class="sig-name descname"><span class="pre">enter_async_context</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">cm</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#contextlib.AsyncExitStack.enter_async_context" title="Link to this definition">¶</a></dt>
  771. <dd><p>Similar to <a class="reference internal" href="#contextlib.ExitStack.enter_context" title="contextlib.ExitStack.enter_context"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ExitStack.enter_context()</span></code></a> but expects an asynchronous context
  772. manager.</p>
  773. <div class="versionchanged">
  774. <p><span class="versionmodified changed">Changed in version 3.11: </span>Raises <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> instead of <a class="reference internal" href="exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a> if <em>cm</em>
  775. is not an asynchronous context manager.</p>
  776. </div>
  777. </dd></dl>
  778. <dl class="py method">
  779. <dt class="sig sig-object py" id="contextlib.AsyncExitStack.push_async_exit">
  780. <span class="sig-name descname"><span class="pre">push_async_exit</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">exit</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#contextlib.AsyncExitStack.push_async_exit" title="Link to this definition">¶</a></dt>
  781. <dd><p>Similar to <a class="reference internal" href="#contextlib.ExitStack.push" title="contextlib.ExitStack.push"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ExitStack.push()</span></code></a> but expects either an asynchronous context manager
  782. or a coroutine function.</p>
  783. </dd></dl>
  784. <dl class="py method">
  785. <dt class="sig sig-object py" id="contextlib.AsyncExitStack.push_async_callback">
  786. <span class="sig-name descname"><span class="pre">push_async_callback</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">callback</span></span></em>, <em class="sig-param"><span class="o"><span class="pre">/</span></span></em>, <em class="sig-param"><span class="o"><span class="pre">*</span></span><span class="n"><span class="pre">args</span></span></em>, <em class="sig-param"><span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">kwds</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#contextlib.AsyncExitStack.push_async_callback" title="Link to this definition">¶</a></dt>
  787. <dd><p>Similar to <a class="reference internal" href="#contextlib.ExitStack.callback" title="contextlib.ExitStack.callback"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ExitStack.callback()</span></code></a> but expects a coroutine function.</p>
  788. </dd></dl>
  789. <dl class="py method">
  790. <dt class="sig sig-object py" id="contextlib.AsyncExitStack.aclose">
  791. <em class="property"><span class="pre">coroutine</span> </em><span class="sig-name descname"><span class="pre">aclose</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#contextlib.AsyncExitStack.aclose" title="Link to this definition">¶</a></dt>
  792. <dd><p>Similar to <a class="reference internal" href="#contextlib.ExitStack.close" title="contextlib.ExitStack.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ExitStack.close()</span></code></a> but properly handles awaitables.</p>
  793. </dd></dl>
  794. <p>Continuing the example for <a class="reference internal" href="#contextlib.asynccontextmanager" title="contextlib.asynccontextmanager"><code class="xref py py-func docutils literal notranslate"><span class="pre">asynccontextmanager()</span></code></a>:</p>
  795. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">async</span> <span class="k">with</span> <span class="n">AsyncExitStack</span><span class="p">()</span> <span class="k">as</span> <span class="n">stack</span><span class="p">:</span>
  796. <span class="n">connections</span> <span class="o">=</span> <span class="p">[</span><span class="k">await</span> <span class="n">stack</span><span class="o">.</span><span class="n">enter_async_context</span><span class="p">(</span><span class="n">get_connection</span><span class="p">())</span>
  797. <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">5</span><span class="p">)]</span>
  798. <span class="c1"># All opened connections will automatically be released at the end of</span>
  799. <span class="c1"># the async with statement, even if attempts to open a connection</span>
  800. <span class="c1"># later in the list raise an exception.</span>
  801. </pre></div>
  802. </div>
  803. <div class="versionadded">
  804. <p><span class="versionmodified added">New in version 3.7.</span></p>
  805. </div>
  806. </dd></dl>
  807. </section>
  808. <section id="examples-and-recipes">
  809. <h2>Examples and Recipes<a class="headerlink" href="#examples-and-recipes" title="Link to this heading">¶</a></h2>
  810. <p>This section describes some examples and recipes for making effective use of
  811. the tools provided by <a class="reference internal" href="#module-contextlib" title="contextlib: Utilities for with-statement contexts."><code class="xref py py-mod docutils literal notranslate"><span class="pre">contextlib</span></code></a>.</p>
  812. <section id="supporting-a-variable-number-of-context-managers">
  813. <h3>Supporting a variable number of context managers<a class="headerlink" href="#supporting-a-variable-number-of-context-managers" title="Link to this heading">¶</a></h3>
  814. <p>The primary use case for <a class="reference internal" href="#contextlib.ExitStack" title="contextlib.ExitStack"><code class="xref py py-class docutils literal notranslate"><span class="pre">ExitStack</span></code></a> is the one given in the class
  815. documentation: supporting a variable number of context managers and other
  816. cleanup operations in a single <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. The variability
  817. may come from the number of context managers needed being driven by user
  818. input (such as opening a user specified collection of files), or from
  819. some of the context managers being optional:</p>
  820. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="n">ExitStack</span><span class="p">()</span> <span class="k">as</span> <span class="n">stack</span><span class="p">:</span>
  821. <span class="k">for</span> <span class="n">resource</span> <span class="ow">in</span> <span class="n">resources</span><span class="p">:</span>
  822. <span class="n">stack</span><span class="o">.</span><span class="n">enter_context</span><span class="p">(</span><span class="n">resource</span><span class="p">)</span>
  823. <span class="k">if</span> <span class="n">need_special_resource</span><span class="p">():</span>
  824. <span class="n">special</span> <span class="o">=</span> <span class="n">acquire_special_resource</span><span class="p">()</span>
  825. <span class="n">stack</span><span class="o">.</span><span class="n">callback</span><span class="p">(</span><span class="n">release_special_resource</span><span class="p">,</span> <span class="n">special</span><span class="p">)</span>
  826. <span class="c1"># Perform operations that use the acquired resources</span>
  827. </pre></div>
  828. </div>
  829. <p>As shown, <a class="reference internal" href="#contextlib.ExitStack" title="contextlib.ExitStack"><code class="xref py py-class docutils literal notranslate"><span class="pre">ExitStack</span></code></a> also makes it quite easy to use <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>
  830. statements to manage arbitrary resources that don’t natively support the
  831. context management protocol.</p>
  832. </section>
  833. <section id="catching-exceptions-from-enter-methods">
  834. <h3>Catching exceptions from <code class="docutils literal notranslate"><span class="pre">__enter__</span></code> methods<a class="headerlink" href="#catching-exceptions-from-enter-methods" title="Link to this heading">¶</a></h3>
  835. <p>It is occasionally desirable to catch exceptions from an <code class="docutils literal notranslate"><span class="pre">__enter__</span></code>
  836. method implementation, <em>without</em> inadvertently catching exceptions from
  837. 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 body or the context manager’s <code class="docutils literal notranslate"><span class="pre">__exit__</span></code>
  838. method. By using <a class="reference internal" href="#contextlib.ExitStack" title="contextlib.ExitStack"><code class="xref py py-class docutils literal notranslate"><span class="pre">ExitStack</span></code></a> the steps in the context management
  839. protocol can be separated slightly in order to allow this:</p>
  840. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">stack</span> <span class="o">=</span> <span class="n">ExitStack</span><span class="p">()</span>
  841. <span class="k">try</span><span class="p">:</span>
  842. <span class="n">x</span> <span class="o">=</span> <span class="n">stack</span><span class="o">.</span><span class="n">enter_context</span><span class="p">(</span><span class="n">cm</span><span class="p">)</span>
  843. <span class="k">except</span> <span class="ne">Exception</span><span class="p">:</span>
  844. <span class="c1"># handle __enter__ exception</span>
  845. <span class="k">else</span><span class="p">:</span>
  846. <span class="k">with</span> <span class="n">stack</span><span class="p">:</span>
  847. <span class="c1"># Handle normal case</span>
  848. </pre></div>
  849. </div>
  850. <p>Actually needing to do this is likely to indicate that the underlying API
  851. should be providing a direct resource management interface for use with
  852. <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#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</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> statements, but not
  853. all APIs are well designed in that regard. When a context manager is the
  854. only resource management API provided, then <a class="reference internal" href="#contextlib.ExitStack" title="contextlib.ExitStack"><code class="xref py py-class docutils literal notranslate"><span class="pre">ExitStack</span></code></a> can make it
  855. easier to handle various situations that can’t be handled directly in a
  856. <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.</p>
  857. </section>
  858. <section id="cleaning-up-in-an-enter-implementation">
  859. <h3>Cleaning up in an <code class="docutils literal notranslate"><span class="pre">__enter__</span></code> implementation<a class="headerlink" href="#cleaning-up-in-an-enter-implementation" title="Link to this heading">¶</a></h3>
  860. <p>As noted in the documentation of <a class="reference internal" href="#contextlib.ExitStack.push" title="contextlib.ExitStack.push"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ExitStack.push()</span></code></a>, this
  861. method can be useful in cleaning up an already allocated resource if later
  862. steps in the <a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> implementation fail.</p>
  863. <p>Here’s an example of doing this for a context manager that accepts resource
  864. acquisition and release functions, along with an optional validation function,
  865. and maps them to the context management protocol:</p>
  866. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">contextlib</span> <span class="kn">import</span> <span class="n">contextmanager</span><span class="p">,</span> <span class="n">AbstractContextManager</span><span class="p">,</span> <span class="n">ExitStack</span>
  867. <span class="k">class</span> <span class="nc">ResourceManager</span><span class="p">(</span><span class="n">AbstractContextManager</span><span class="p">):</span>
  868. <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">acquire_resource</span><span class="p">,</span> <span class="n">release_resource</span><span class="p">,</span> <span class="n">check_resource_ok</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
  869. <span class="bp">self</span><span class="o">.</span><span class="n">acquire_resource</span> <span class="o">=</span> <span class="n">acquire_resource</span>
  870. <span class="bp">self</span><span class="o">.</span><span class="n">release_resource</span> <span class="o">=</span> <span class="n">release_resource</span>
  871. <span class="k">if</span> <span class="n">check_resource_ok</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
  872. <span class="k">def</span> <span class="nf">check_resource_ok</span><span class="p">(</span><span class="n">resource</span><span class="p">):</span>
  873. <span class="k">return</span> <span class="kc">True</span>
  874. <span class="bp">self</span><span class="o">.</span><span class="n">check_resource_ok</span> <span class="o">=</span> <span class="n">check_resource_ok</span>
  875. <span class="nd">@contextmanager</span>
  876. <span class="k">def</span> <span class="nf">_cleanup_on_error</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  877. <span class="k">with</span> <span class="n">ExitStack</span><span class="p">()</span> <span class="k">as</span> <span class="n">stack</span><span class="p">:</span>
  878. <span class="n">stack</span><span class="o">.</span><span class="n">push</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
  879. <span class="k">yield</span>
  880. <span class="c1"># The validation check passed and didn&#39;t raise an exception</span>
  881. <span class="c1"># Accordingly, we want to keep the resource, and pass it</span>
  882. <span class="c1"># back to our caller</span>
  883. <span class="n">stack</span><span class="o">.</span><span class="n">pop_all</span><span class="p">()</span>
  884. <span class="k">def</span> <span class="fm">__enter__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  885. <span class="n">resource</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">acquire_resource</span><span class="p">()</span>
  886. <span class="k">with</span> <span class="bp">self</span><span class="o">.</span><span class="n">_cleanup_on_error</span><span class="p">():</span>
  887. <span class="k">if</span> <span class="ow">not</span> <span class="bp">self</span><span class="o">.</span><span class="n">check_resource_ok</span><span class="p">(</span><span class="n">resource</span><span class="p">):</span>
  888. <span class="n">msg</span> <span class="o">=</span> <span class="s2">&quot;Failed validation for </span><span class="si">{!r}</span><span class="s2">&quot;</span>
  889. <span class="k">raise</span> <span class="ne">RuntimeError</span><span class="p">(</span><span class="n">msg</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">resource</span><span class="p">))</span>
  890. <span class="k">return</span> <span class="n">resource</span>
  891. <span class="k">def</span> <span class="fm">__exit__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">exc_details</span><span class="p">):</span>
  892. <span class="c1"># We don&#39;t need to duplicate any of our resource release logic</span>
  893. <span class="bp">self</span><span class="o">.</span><span class="n">release_resource</span><span class="p">()</span>
  894. </pre></div>
  895. </div>
  896. </section>
  897. <section id="replacing-any-use-of-try-finally-and-flag-variables">
  898. <h3>Replacing any use of <code class="docutils literal notranslate"><span class="pre">try-finally</span></code> and flag variables<a class="headerlink" href="#replacing-any-use-of-try-finally-and-flag-variables" title="Link to this heading">¶</a></h3>
  899. <p>A pattern you will sometimes see is a <code class="docutils literal notranslate"><span class="pre">try-finally</span></code> statement with a flag
  900. variable to indicate whether or not the body of the <code class="docutils literal notranslate"><span class="pre">finally</span></code> clause should
  901. be executed. In its simplest form (that can’t already be handled just by
  902. using an <code class="docutils literal notranslate"><span class="pre">except</span></code> clause instead), it looks something like this:</p>
  903. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">cleanup_needed</span> <span class="o">=</span> <span class="kc">True</span>
  904. <span class="k">try</span><span class="p">:</span>
  905. <span class="n">result</span> <span class="o">=</span> <span class="n">perform_operation</span><span class="p">()</span>
  906. <span class="k">if</span> <span class="n">result</span><span class="p">:</span>
  907. <span class="n">cleanup_needed</span> <span class="o">=</span> <span class="kc">False</span>
  908. <span class="k">finally</span><span class="p">:</span>
  909. <span class="k">if</span> <span class="n">cleanup_needed</span><span class="p">:</span>
  910. <span class="n">cleanup_resources</span><span class="p">()</span>
  911. </pre></div>
  912. </div>
  913. <p>As with any <code class="docutils literal notranslate"><span class="pre">try</span></code> statement based code, this can cause problems for
  914. development and review, because the setup code and the cleanup code can end
  915. up being separated by arbitrarily long sections of code.</p>
  916. <p><a class="reference internal" href="#contextlib.ExitStack" title="contextlib.ExitStack"><code class="xref py py-class docutils literal notranslate"><span class="pre">ExitStack</span></code></a> makes it possible to instead register a callback for
  917. execution at the end of a <code class="docutils literal notranslate"><span class="pre">with</span></code> statement, and then later decide to skip
  918. executing that callback:</p>
  919. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">contextlib</span> <span class="kn">import</span> <span class="n">ExitStack</span>
  920. <span class="k">with</span> <span class="n">ExitStack</span><span class="p">()</span> <span class="k">as</span> <span class="n">stack</span><span class="p">:</span>
  921. <span class="n">stack</span><span class="o">.</span><span class="n">callback</span><span class="p">(</span><span class="n">cleanup_resources</span><span class="p">)</span>
  922. <span class="n">result</span> <span class="o">=</span> <span class="n">perform_operation</span><span class="p">()</span>
  923. <span class="k">if</span> <span class="n">result</span><span class="p">:</span>
  924. <span class="n">stack</span><span class="o">.</span><span class="n">pop_all</span><span class="p">()</span>
  925. </pre></div>
  926. </div>
  927. <p>This allows the intended cleanup up behaviour to be made explicit up front,
  928. rather than requiring a separate flag variable.</p>
  929. <p>If a particular application uses this pattern a lot, it can be simplified
  930. even further by means of a small helper class:</p>
  931. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">contextlib</span> <span class="kn">import</span> <span class="n">ExitStack</span>
  932. <span class="k">class</span> <span class="nc">Callback</span><span class="p">(</span><span class="n">ExitStack</span><span class="p">):</span>
  933. <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">callback</span><span class="p">,</span> <span class="o">/</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwds</span><span class="p">):</span>
  934. <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="fm">__init__</span><span class="p">()</span>
  935. <span class="bp">self</span><span class="o">.</span><span class="n">callback</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> <span class="o">**</span><span class="n">kwds</span><span class="p">)</span>
  936. <span class="k">def</span> <span class="nf">cancel</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  937. <span class="bp">self</span><span class="o">.</span><span class="n">pop_all</span><span class="p">()</span>
  938. <span class="k">with</span> <span class="n">Callback</span><span class="p">(</span><span class="n">cleanup_resources</span><span class="p">)</span> <span class="k">as</span> <span class="n">cb</span><span class="p">:</span>
  939. <span class="n">result</span> <span class="o">=</span> <span class="n">perform_operation</span><span class="p">()</span>
  940. <span class="k">if</span> <span class="n">result</span><span class="p">:</span>
  941. <span class="n">cb</span><span class="o">.</span><span class="n">cancel</span><span class="p">()</span>
  942. </pre></div>
  943. </div>
  944. <p>If the resource cleanup isn’t already neatly bundled into a standalone
  945. function, then it is still possible to use the decorator form of
  946. <a class="reference internal" href="#contextlib.ExitStack.callback" title="contextlib.ExitStack.callback"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ExitStack.callback()</span></code></a> to declare the resource cleanup in
  947. advance:</p>
  948. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">contextlib</span> <span class="kn">import</span> <span class="n">ExitStack</span>
  949. <span class="k">with</span> <span class="n">ExitStack</span><span class="p">()</span> <span class="k">as</span> <span class="n">stack</span><span class="p">:</span>
  950. <span class="nd">@stack</span><span class="o">.</span><span class="n">callback</span>
  951. <span class="k">def</span> <span class="nf">cleanup_resources</span><span class="p">():</span>
  952. <span class="o">...</span>
  953. <span class="n">result</span> <span class="o">=</span> <span class="n">perform_operation</span><span class="p">()</span>
  954. <span class="k">if</span> <span class="n">result</span><span class="p">:</span>
  955. <span class="n">stack</span><span class="o">.</span><span class="n">pop_all</span><span class="p">()</span>
  956. </pre></div>
  957. </div>
  958. <p>Due to the way the decorator protocol works, a callback function
  959. declared this way cannot take any parameters. Instead, any resources to
  960. be released must be accessed as closure variables.</p>
  961. </section>
  962. <section id="using-a-context-manager-as-a-function-decorator">
  963. <h3>Using a context manager as a function decorator<a class="headerlink" href="#using-a-context-manager-as-a-function-decorator" title="Link to this heading">¶</a></h3>
  964. <p><a class="reference internal" href="#contextlib.ContextDecorator" title="contextlib.ContextDecorator"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContextDecorator</span></code></a> makes it possible to use a context manager in
  965. both an ordinary <code class="docutils literal notranslate"><span class="pre">with</span></code> statement and also as a function decorator.</p>
  966. <p>For example, it is sometimes useful to wrap functions or groups of statements
  967. with a logger that can track the time of entry and time of exit. Rather than
  968. writing both a function decorator and a context manager for the task,
  969. inheriting from <a class="reference internal" href="#contextlib.ContextDecorator" title="contextlib.ContextDecorator"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContextDecorator</span></code></a> provides both capabilities in a
  970. single definition:</p>
  971. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">contextlib</span> <span class="kn">import</span> <span class="n">ContextDecorator</span>
  972. <span class="kn">import</span> <span class="nn">logging</span>
  973. <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">INFO</span><span class="p">)</span>
  974. <span class="k">class</span> <span class="nc">track_entry_and_exit</span><span class="p">(</span><span class="n">ContextDecorator</span><span class="p">):</span>
  975. <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">):</span>
  976. <span class="bp">self</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="n">name</span>
  977. <span class="k">def</span> <span class="fm">__enter__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  978. <span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;Entering: </span><span class="si">%s</span><span class="s1">&#39;</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">name</span><span class="p">)</span>
  979. <span class="k">def</span> <span class="fm">__exit__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">exc_type</span><span class="p">,</span> <span class="n">exc</span><span class="p">,</span> <span class="n">exc_tb</span><span class="p">):</span>
  980. <span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;Exiting: </span><span class="si">%s</span><span class="s1">&#39;</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">name</span><span class="p">)</span>
  981. </pre></div>
  982. </div>
  983. <p>Instances of this class can be used as both a context manager:</p>
  984. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="n">track_entry_and_exit</span><span class="p">(</span><span class="s1">&#39;widget loader&#39;</span><span class="p">):</span>
  985. <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;Some time consuming activity goes here&#39;</span><span class="p">)</span>
  986. <span class="n">load_widget</span><span class="p">()</span>
  987. </pre></div>
  988. </div>
  989. <p>And also as a function decorator:</p>
  990. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="nd">@track_entry_and_exit</span><span class="p">(</span><span class="s1">&#39;widget loader&#39;</span><span class="p">)</span>
  991. <span class="k">def</span> <span class="nf">activity</span><span class="p">():</span>
  992. <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;Some time consuming activity goes here&#39;</span><span class="p">)</span>
  993. <span class="n">load_widget</span><span class="p">()</span>
  994. </pre></div>
  995. </div>
  996. <p>Note that there is one additional limitation when using context managers
  997. as function decorators: there’s no way to access the return value of
  998. <a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a>. If that value is needed, then it is still necessary to use
  999. an explicit <code class="docutils literal notranslate"><span class="pre">with</span></code> statement.</p>
  1000. <div class="admonition seealso">
  1001. <p class="admonition-title">See also</p>
  1002. <dl class="simple">
  1003. <dt><span class="target" id="index-0"></span><a class="pep reference external" href="https://peps.python.org/pep-0343/"><strong>PEP 343</strong></a> - The “with” statement</dt><dd><p>The specification, background, and examples for the Python <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>
  1004. statement.</p>
  1005. </dd>
  1006. </dl>
  1007. </div>
  1008. </section>
  1009. </section>
  1010. <section id="single-use-reusable-and-reentrant-context-managers">
  1011. <span id="single-use-reusable-and-reentrant-cms"></span><h2>Single use, reusable and reentrant context managers<a class="headerlink" href="#single-use-reusable-and-reentrant-context-managers" title="Link to this heading">¶</a></h2>
  1012. <p>Most context managers are written in a way that means they can only be
  1013. used effectively in a <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 once. These single use
  1014. context managers must be created afresh each time they’re used -
  1015. attempting to use them a second time will trigger an exception or
  1016. otherwise not work correctly.</p>
  1017. <p>This common limitation means that it is generally advisable to create
  1018. context managers directly in the header of 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
  1019. where they are used (as shown in all of the usage examples above).</p>
  1020. <p>Files are an example of effectively single use context managers, since
  1021. the first <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 will close the file, preventing any
  1022. further IO operations using that file object.</p>
  1023. <p>Context managers created using <a class="reference internal" href="#contextlib.contextmanager" title="contextlib.contextmanager"><code class="xref py py-func docutils literal notranslate"><span class="pre">contextmanager()</span></code></a> are also single use
  1024. context managers, and will complain about the underlying generator failing
  1025. to yield if an attempt is made to use them a second time:</p>
  1026. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">contextlib</span> <span class="kn">import</span> <span class="n">contextmanager</span>
  1027. <span class="gp">&gt;&gt;&gt; </span><span class="nd">@contextmanager</span>
  1028. <span class="gp">... </span><span class="k">def</span> <span class="nf">singleuse</span><span class="p">():</span>
  1029. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Before&quot;</span><span class="p">)</span>
  1030. <span class="gp">... </span> <span class="k">yield</span>
  1031. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;After&quot;</span><span class="p">)</span>
  1032. <span class="gp">...</span>
  1033. <span class="gp">&gt;&gt;&gt; </span><span class="n">cm</span> <span class="o">=</span> <span class="n">singleuse</span><span class="p">()</span>
  1034. <span class="gp">&gt;&gt;&gt; </span><span class="k">with</span> <span class="n">cm</span><span class="p">:</span>
  1035. <span class="gp">... </span> <span class="k">pass</span>
  1036. <span class="gp">...</span>
  1037. <span class="go">Before</span>
  1038. <span class="go">After</span>
  1039. <span class="gp">&gt;&gt;&gt; </span><span class="k">with</span> <span class="n">cm</span><span class="p">:</span>
  1040. <span class="gp">... </span> <span class="k">pass</span>
  1041. <span class="gp">...</span>
  1042. <span class="gt">Traceback (most recent call last):</span>
  1043. <span class="w"> </span><span class="o">...</span>
  1044. <span class="gr">RuntimeError</span>: <span class="n">generator didn&#39;t yield</span>
  1045. </pre></div>
  1046. </div>
  1047. <section id="reentrant-context-managers">
  1048. <span id="reentrant-cms"></span><h3>Reentrant context managers<a class="headerlink" href="#reentrant-context-managers" title="Link to this heading">¶</a></h3>
  1049. <p>More sophisticated context managers may be “reentrant”. These context
  1050. managers can not only be used in multiple <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> statements,
  1051. but may also be used <em>inside</em> a <code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code> statement that is already
  1052. using the same context manager.</p>
  1053. <p><a class="reference internal" href="threading.html#threading.RLock" title="threading.RLock"><code class="xref py py-class docutils literal notranslate"><span class="pre">threading.RLock</span></code></a> is an example of a reentrant context manager, as are
  1054. <a class="reference internal" href="#contextlib.suppress" title="contextlib.suppress"><code class="xref py py-func docutils literal notranslate"><span class="pre">suppress()</span></code></a>, <a class="reference internal" href="#contextlib.redirect_stdout" title="contextlib.redirect_stdout"><code class="xref py py-func docutils literal notranslate"><span class="pre">redirect_stdout()</span></code></a>, and <a class="reference internal" href="#contextlib.chdir" title="contextlib.chdir"><code class="xref py py-func docutils literal notranslate"><span class="pre">chdir()</span></code></a>. Here’s a very
  1055. simple example of reentrant use:</p>
  1056. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">contextlib</span> <span class="kn">import</span> <span class="n">redirect_stdout</span>
  1057. <span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">io</span> <span class="kn">import</span> <span class="n">StringIO</span>
  1058. <span class="gp">&gt;&gt;&gt; </span><span class="n">stream</span> <span class="o">=</span> <span class="n">StringIO</span><span class="p">()</span>
  1059. <span class="gp">&gt;&gt;&gt; </span><span class="n">write_to_stream</span> <span class="o">=</span> <span class="n">redirect_stdout</span><span class="p">(</span><span class="n">stream</span><span class="p">)</span>
  1060. <span class="gp">&gt;&gt;&gt; </span><span class="k">with</span> <span class="n">write_to_stream</span><span class="p">:</span>
  1061. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;This is written to the stream rather than stdout&quot;</span><span class="p">)</span>
  1062. <span class="gp">... </span> <span class="k">with</span> <span class="n">write_to_stream</span><span class="p">:</span>
  1063. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;This is also written to the stream&quot;</span><span class="p">)</span>
  1064. <span class="gp">...</span>
  1065. <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="s2">&quot;This is written directly to stdout&quot;</span><span class="p">)</span>
  1066. <span class="go">This is written directly to stdout</span>
  1067. <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">stream</span><span class="o">.</span><span class="n">getvalue</span><span class="p">())</span>
  1068. <span class="go">This is written to the stream rather than stdout</span>
  1069. <span class="go">This is also written to the stream</span>
  1070. </pre></div>
  1071. </div>
  1072. <p>Real world examples of reentrancy are more likely to involve multiple
  1073. functions calling each other and hence be far more complicated than this
  1074. example.</p>
  1075. <p>Note also that being reentrant is <em>not</em> the same thing as being thread safe.
  1076. <a class="reference internal" href="#contextlib.redirect_stdout" title="contextlib.redirect_stdout"><code class="xref py py-func docutils literal notranslate"><span class="pre">redirect_stdout()</span></code></a>, for example, is definitely not thread safe, as it
  1077. makes a global modification to the system state by binding <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>
  1078. to a different stream.</p>
  1079. </section>
  1080. <section id="reusable-context-managers">
  1081. <span id="reusable-cms"></span><h3>Reusable context managers<a class="headerlink" href="#reusable-context-managers" title="Link to this heading">¶</a></h3>
  1082. <p>Distinct from both single use and reentrant context managers are “reusable”
  1083. context managers (or, to be completely explicit, “reusable, but not
  1084. reentrant” context managers, since reentrant context managers are also
  1085. reusable). These context managers support being used multiple times, but
  1086. will fail (or otherwise not work correctly) if the specific context manager
  1087. instance has already been used in a containing with statement.</p>
  1088. <p><a class="reference internal" href="threading.html#threading.Lock" title="threading.Lock"><code class="xref py py-class docutils literal notranslate"><span class="pre">threading.Lock</span></code></a> is an example of a reusable, but not reentrant,
  1089. context manager (for a reentrant lock, it is necessary to use
  1090. <a class="reference internal" href="threading.html#threading.RLock" title="threading.RLock"><code class="xref py py-class docutils literal notranslate"><span class="pre">threading.RLock</span></code></a> instead).</p>
  1091. <p>Another example of a reusable, but not reentrant, context manager is
  1092. <a class="reference internal" href="#contextlib.ExitStack" title="contextlib.ExitStack"><code class="xref py py-class docutils literal notranslate"><span class="pre">ExitStack</span></code></a>, as it invokes <em>all</em> currently registered callbacks
  1093. when leaving any with statement, regardless of where those callbacks
  1094. were added:</p>
  1095. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">contextlib</span> <span class="kn">import</span> <span class="n">ExitStack</span>
  1096. <span class="gp">&gt;&gt;&gt; </span><span class="n">stack</span> <span class="o">=</span> <span class="n">ExitStack</span><span class="p">()</span>
  1097. <span class="gp">&gt;&gt;&gt; </span><span class="k">with</span> <span class="n">stack</span><span class="p">:</span>
  1098. <span class="gp">... </span> <span class="n">stack</span><span class="o">.</span><span class="n">callback</span><span class="p">(</span><span class="nb">print</span><span class="p">,</span> <span class="s2">&quot;Callback: from first context&quot;</span><span class="p">)</span>
  1099. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Leaving first context&quot;</span><span class="p">)</span>
  1100. <span class="gp">...</span>
  1101. <span class="go">Leaving first context</span>
  1102. <span class="go">Callback: from first context</span>
  1103. <span class="gp">&gt;&gt;&gt; </span><span class="k">with</span> <span class="n">stack</span><span class="p">:</span>
  1104. <span class="gp">... </span> <span class="n">stack</span><span class="o">.</span><span class="n">callback</span><span class="p">(</span><span class="nb">print</span><span class="p">,</span> <span class="s2">&quot;Callback: from second context&quot;</span><span class="p">)</span>
  1105. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Leaving second context&quot;</span><span class="p">)</span>
  1106. <span class="gp">...</span>
  1107. <span class="go">Leaving second context</span>
  1108. <span class="go">Callback: from second context</span>
  1109. <span class="gp">&gt;&gt;&gt; </span><span class="k">with</span> <span class="n">stack</span><span class="p">:</span>
  1110. <span class="gp">... </span> <span class="n">stack</span><span class="o">.</span><span class="n">callback</span><span class="p">(</span><span class="nb">print</span><span class="p">,</span> <span class="s2">&quot;Callback: from outer context&quot;</span><span class="p">)</span>
  1111. <span class="gp">... </span> <span class="k">with</span> <span class="n">stack</span><span class="p">:</span>
  1112. <span class="gp">... </span> <span class="n">stack</span><span class="o">.</span><span class="n">callback</span><span class="p">(</span><span class="nb">print</span><span class="p">,</span> <span class="s2">&quot;Callback: from inner context&quot;</span><span class="p">)</span>
  1113. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Leaving inner context&quot;</span><span class="p">)</span>
  1114. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Leaving outer context&quot;</span><span class="p">)</span>
  1115. <span class="gp">...</span>
  1116. <span class="go">Leaving inner context</span>
  1117. <span class="go">Callback: from inner context</span>
  1118. <span class="go">Callback: from outer context</span>
  1119. <span class="go">Leaving outer context</span>
  1120. </pre></div>
  1121. </div>
  1122. <p>As the output from the example shows, reusing a single stack object across
  1123. multiple with statements works correctly, but attempting to nest them
  1124. will cause the stack to be cleared at the end of the innermost with
  1125. statement, which is unlikely to be desirable behaviour.</p>
  1126. <p>Using separate <a class="reference internal" href="#contextlib.ExitStack" title="contextlib.ExitStack"><code class="xref py py-class docutils literal notranslate"><span class="pre">ExitStack</span></code></a> instances instead of reusing a single
  1127. instance avoids that problem:</p>
  1128. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">contextlib</span> <span class="kn">import</span> <span class="n">ExitStack</span>
  1129. <span class="gp">&gt;&gt;&gt; </span><span class="k">with</span> <span class="n">ExitStack</span><span class="p">()</span> <span class="k">as</span> <span class="n">outer_stack</span><span class="p">:</span>
  1130. <span class="gp">... </span> <span class="n">outer_stack</span><span class="o">.</span><span class="n">callback</span><span class="p">(</span><span class="nb">print</span><span class="p">,</span> <span class="s2">&quot;Callback: from outer context&quot;</span><span class="p">)</span>
  1131. <span class="gp">... </span> <span class="k">with</span> <span class="n">ExitStack</span><span class="p">()</span> <span class="k">as</span> <span class="n">inner_stack</span><span class="p">:</span>
  1132. <span class="gp">... </span> <span class="n">inner_stack</span><span class="o">.</span><span class="n">callback</span><span class="p">(</span><span class="nb">print</span><span class="p">,</span> <span class="s2">&quot;Callback: from inner context&quot;</span><span class="p">)</span>
  1133. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Leaving inner context&quot;</span><span class="p">)</span>
  1134. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Leaving outer context&quot;</span><span class="p">)</span>
  1135. <span class="gp">...</span>
  1136. <span class="go">Leaving inner context</span>
  1137. <span class="go">Callback: from inner context</span>
  1138. <span class="go">Leaving outer context</span>
  1139. <span class="go">Callback: from outer context</span>
  1140. </pre></div>
  1141. </div>
  1142. </section>
  1143. </section>
  1144. </section>
  1145. <div class="clearer"></div>
  1146. </div>
  1147. </div>
  1148. </div>
  1149. <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
  1150. <div class="sphinxsidebarwrapper">
  1151. <div>
  1152. <h3><a href="../contents.html">Table of Contents</a></h3>
  1153. <ul>
  1154. <li><a class="reference internal" href="#"><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><ul>
  1155. <li><a class="reference internal" href="#utilities">Utilities</a></li>
  1156. <li><a class="reference internal" href="#examples-and-recipes">Examples and Recipes</a><ul>
  1157. <li><a class="reference internal" href="#supporting-a-variable-number-of-context-managers">Supporting a variable number of context managers</a></li>
  1158. <li><a class="reference internal" href="#catching-exceptions-from-enter-methods">Catching exceptions from <code class="docutils literal notranslate"><span class="pre">__enter__</span></code> methods</a></li>
  1159. <li><a class="reference internal" href="#cleaning-up-in-an-enter-implementation">Cleaning up in an <code class="docutils literal notranslate"><span class="pre">__enter__</span></code> implementation</a></li>
  1160. <li><a class="reference internal" href="#replacing-any-use-of-try-finally-and-flag-variables">Replacing any use of <code class="docutils literal notranslate"><span class="pre">try-finally</span></code> and flag variables</a></li>
  1161. <li><a class="reference internal" href="#using-a-context-manager-as-a-function-decorator">Using a context manager as a function decorator</a></li>
  1162. </ul>
  1163. </li>
  1164. <li><a class="reference internal" href="#single-use-reusable-and-reentrant-context-managers">Single use, reusable and reentrant context managers</a><ul>
  1165. <li><a class="reference internal" href="#reentrant-context-managers">Reentrant context managers</a></li>
  1166. <li><a class="reference internal" href="#reusable-context-managers">Reusable context managers</a></li>
  1167. </ul>
  1168. </li>
  1169. </ul>
  1170. </li>
  1171. </ul>
  1172. </div>
  1173. <div>
  1174. <h4>Previous topic</h4>
  1175. <p class="topless"><a href="dataclasses.html"
  1176. title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">dataclasses</span></code> — Data Classes</a></p>
  1177. </div>
  1178. <div>
  1179. <h4>Next topic</h4>
  1180. <p class="topless"><a href="abc.html"
  1181. title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">abc</span></code> — Abstract Base Classes</a></p>
  1182. </div>
  1183. <div role="note" aria-label="source link">
  1184. <h3>This Page</h3>
  1185. <ul class="this-page-menu">
  1186. <li><a href="../bugs.html">Report a Bug</a></li>
  1187. <li>
  1188. <a href="https://github.com/python/cpython/blob/main/Doc/library/contextlib.rst"
  1189. rel="nofollow">Show Source
  1190. </a>
  1191. </li>
  1192. </ul>
  1193. </div>
  1194. </div>
  1195. <div id="sidebarbutton" title="Collapse sidebar">
  1196. <span>«</span>
  1197. </div>
  1198. </div>
  1199. <div class="clearer"></div>
  1200. </div>
  1201. <div class="related" role="navigation" aria-label="related navigation">
  1202. <h3>Navigation</h3>
  1203. <ul>
  1204. <li class="right" style="margin-right: 10px">
  1205. <a href="../genindex.html" title="General Index"
  1206. >index</a></li>
  1207. <li class="right" >
  1208. <a href="../py-modindex.html" title="Python Module Index"
  1209. >modules</a> |</li>
  1210. <li class="right" >
  1211. <a href="abc.html" title="abc — Abstract Base Classes"
  1212. >next</a> |</li>
  1213. <li class="right" >
  1214. <a href="dataclasses.html" title="dataclasses — Data Classes"
  1215. >previous</a> |</li>
  1216. <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  1217. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  1218. <li class="switchers">
  1219. <div class="language_switcher_placeholder"></div>
  1220. <div class="version_switcher_placeholder"></div>
  1221. </li>
  1222. <li>
  1223. </li>
  1224. <li id="cpython-language-and-version">
  1225. <a href="../index.html">3.12.3 Documentation</a> &#187;
  1226. </li>
  1227. <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
  1228. <li class="nav-item nav-item-2"><a href="python.html" >Python Runtime Services</a> &#187;</li>
  1229. <li class="nav-item nav-item-this"><a href=""><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></li>
  1230. <li class="right">
  1231. <div class="inline-search" role="search">
  1232. <form class="inline-search" action="../search.html" method="get">
  1233. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
  1234. <input type="submit" value="Go" />
  1235. </form>
  1236. </div>
  1237. |
  1238. </li>
  1239. <li class="right">
  1240. <label class="theme-selector-label">
  1241. Theme
  1242. <select class="theme-selector" oninput="activateTheme(this.value)">
  1243. <option value="auto" selected>Auto</option>
  1244. <option value="light">Light</option>
  1245. <option value="dark">Dark</option>
  1246. </select>
  1247. </label> |</li>
  1248. </ul>
  1249. </div>
  1250. <div class="footer">
  1251. &copy;
  1252. <a href="../copyright.html">
  1253. Copyright
  1254. </a>
  1255. 2001-2024, Python Software Foundation.
  1256. <br />
  1257. This page is licensed under the Python Software Foundation License Version 2.
  1258. <br />
  1259. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
  1260. <br />
  1261. See <a href="/license.html">History and License</a> for more information.<br />
  1262. <br />
  1263. The Python Software Foundation is a non-profit corporation.
  1264. <a href="https://www.python.org/psf/donations/">Please donate.</a>
  1265. <br />
  1266. <br />
  1267. Last updated on Apr 09, 2024 (13:47 UTC).
  1268. <a href="/bugs.html">Found a bug</a>?
  1269. <br />
  1270. Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 7.2.6.
  1271. </div>
  1272. </body>
  1273. </html>
上海开阖软件有限公司 沪ICP备12045867号-1