Team Ai
Apppublic

parthtamu/rag-code-assistant

sourceHugging Faceupdated 7mo agoView on Hugging Face
0likes
devmode.html558 linesDownload Raw Back to docs
1<!DOCTYPE html>2 3<html lang="en" data-content_root="../">4  <head>5    <meta charset="utf-8" />6    <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" />7<meta property="og:title" content="Python Development Mode" />8<meta property="og:type" content="website" />9<meta property="og:url" content="https://docs.python.org/3/library/devmode.html" />10<meta property="og:site_name" content="Python documentation" />11<meta property="og:description" content="The Python Development Mode introduces additional runtime checks that are too expensive to be enabled by default. It should not be more verbose than the default if the code is correct; new warnings..." />12<meta property="og:image:width" content="1146" />13<meta property="og:image:height" content="600" />14<meta property="og:image" content="https://docs.python.org/3.15/_images/social_previews/summary_library_devmode_3f96727c.png" />15<meta property="og:image:alt" content="The Python Development Mode introduces additional runtime checks that are too expensive to be enabled by default. It should not be more verbose than the default if the code is correct; new warnings..." />16<meta name="description" content="The Python Development Mode introduces additional runtime checks that are too expensive to be enabled by default. It should not be more verbose than the default if the code is correct; new warnings..." />17<meta name="twitter:card" content="summary_large_image" />18<meta name="theme-color" content="#3776ab">19 20    <title>Python Development Mode &#8212; Python 3.15.0a6 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">21    22    <link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" />23    <link rel="stylesheet" type="text/css" href="../_static/classic.css?v=234b1a7c" />24    <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=89a2f22a" />25    <link rel="stylesheet" type="text/css" href="../_static/profiling-sampling-visualization.css?v=0c2600ae" />26    <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" />27    28    <script src="../_static/documentation_options.js?v=6b7c9ff5"></script>29    <script src="../_static/doctools.js?v=9bcbadda"></script>30    <script src="../_static/sphinx_highlight.js?v=dc90522c"></script>31    <script src="../_static/profiling-sampling-visualization.js?v=9811ed04"></script>32    33    <script src="../_static/sidebar.js"></script>34    35    <link rel="search" type="application/opensearchdescription+xml"36          title="Search within Python 3.15.0a6 documentation"37          href="../_static/opensearch.xml"/>38    <link rel="author" title="About these documents" href="../about.html" />39    <link rel="index" title="Index" href="../genindex.html" />40    <link rel="search" title="Search" href="../search.html" />41    <link rel="copyright" title="Copyright" href="../copyright.html" />42    <link rel="next" title="doctest — Test interactive Python examples" href="doctest.html" />43    <link rel="prev" title="pydoc — Documentation generator and online help system" href="pydoc.html" />44    45      46      <script defer file-types="bz2,epub,zip" data-domain="docs.python.org" src="https://analytics.python.org/js/script.file-downloads.outbound-links.js"></script>47      48      <link rel="canonical" href="https://docs.python.org/3/library/devmode.html">49      50    51 52    53    <style>54      @media only screen {55        table.full-width-table {56            width: 100%;57        }58      }59    </style>60<link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">61    <link rel="shortcut icon" type="image/png" href="../_static/py.svg">62            <script type="text/javascript" src="../_static/copybutton.js"></script>63            <script type="text/javascript" src="../_static/menu.js"></script>64            <script type="text/javascript" src="../_static/search-focus.js"></script>65            <script type="text/javascript" src="../_static/themetoggle.js"></script> 66            <script type="text/javascript" src="../_static/rtd_switcher.js"></script>67            <meta name="readthedocs-addons-api-version" content="1">68 69  </head>70<body>71<div class="mobile-nav">72    <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"73           aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu">74    <nav class="nav-content" role="navigation">75        <label for="menuToggler" class="toggler__label">76            <span></span>77        </label>78        <span class="nav-items-wrapper">79            <a href="https://www.python.org/" class="nav-logo">80                <img src="../_static/py.svg" alt="Python logo">81            </a>82            <span class="version_switcher_placeholder"></span>83            <form role="search" class="search" action="../search.html" method="get">84                <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">85                    <path fill-rule="nonzero" fill="currentColor" d="M15.5 14h-.79l-.28-.27a6.5 6.5 0 001.48-5.34c-.47-2.78-2.79-5-5.59-5.34a6.505 6.505 0 00-7.27 7.27c.34 2.8 2.56 5.12 5.34 5.59a6.5 6.5 0 005.34-1.48l.27.28v.79l4.25 4.25c.41.41 1.08.41 1.49 0 .41-.41.41-1.08 0-1.49L15.5 14zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"></path>86                </svg>87                <input placeholder="Quick search" aria-label="Quick search" type="search" name="q">88                <input type="submit" value="Go">89            </form>90        </span>91    </nav>92    <div class="menu-wrapper">93        <nav class="menu" role="navigation" aria-label="main navigation">94            <div class="language_switcher_placeholder"></div>95            96<label class="theme-selector-label">97    Theme98    <select class="theme-selector" oninput="activateTheme(this.value)">99        <option value="auto" selected>Auto</option>100        <option value="light">Light</option>101        <option value="dark">Dark</option>102    </select>103</label>104  <div>105    <h3><a href="../contents.html">Table of Contents</a></h3>106    <ul>107<li><a class="reference internal" href="#">Python Development Mode</a><ul>108<li><a class="reference internal" href="#effects-of-the-python-development-mode">Effects of the Python Development Mode</a></li>109<li><a class="reference internal" href="#resourcewarning-example">ResourceWarning Example</a></li>110<li><a class="reference internal" href="#bad-file-descriptor-error-example">Bad file descriptor error example</a></li>111</ul>112</li>113</ul>114 115  </div>116  <div>117    <h4>Previous topic</h4>118    <p class="topless"><a href="pydoc.html"119                          title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">pydoc</span></code> — Documentation generator and online help system</a></p>120  </div>121  <div>122    <h4>Next topic</h4>123    <p class="topless"><a href="doctest.html"124                          title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code> — Test interactive Python examples</a></p>125  </div>126  <script>127    document.addEventListener('DOMContentLoaded', () => {128        const title = document.querySelector('meta[property="og:title"]').content;129        const elements = document.querySelectorAll('.improvepage');130        const pageurl = window.location.href.split('?')[0];131        elements.forEach(element => {132            const url = new URL(element.href.split('?')[0].replace("-nojs", ""));133            url.searchParams.set('pagetitle', title);134            url.searchParams.set('pageurl', pageurl);135            url.searchParams.set('pagesource', "library/devmode.rst");136            element.href = url.toString();137        });138    });139  </script>140  <div role="note" aria-label="source link">141    <h3>This page</h3>142    <ul class="this-page-menu">143      <li><a href="../bugs.html">Report a bug</a></li>144      <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li>145      <li>146        <a href="https://github.com/python/cpython/blob/main/Doc/library/devmode.rst?plain=1"147            rel="nofollow">Show source148        </a>149      </li>150      151    </ul>152  </div>153        </nav>154    </div>155</div>156 157  158    <div class="related" role="navigation" aria-label="Related">159      <h3>Navigation</h3>160      <ul>161        <li class="right" style="margin-right: 10px">162          <a href="../genindex.html" title="General Index"163             accesskey="I">index</a></li>164        <li class="right" >165          <a href="../py-modindex.html" title="Python Module Index"166             >modules</a> |</li>167        <li class="right" >168          <a href="doctest.html" title="doctest — Test interactive Python examples"169             accesskey="N">next</a> |</li>170        <li class="right" >171          <a href="pydoc.html" title="pydoc — Documentation generator and online help system"172             accesskey="P">previous</a> |</li>173 174          <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li>175          <li><a href="https://www.python.org/">Python</a> &#187;</li>176          <li class="switchers">177            <div class="language_switcher_placeholder"></div>178            <div class="version_switcher_placeholder"></div>179          </li>180          <li>181              182          </li>183    <li id="cpython-language-and-version">184      <a href="../index.html">3.15.0a6 Documentation</a> &#187;185    </li>186 187          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>188          <li class="nav-item nav-item-2"><a href="development.html" accesskey="U">Development Tools</a> &#187;</li>189        <li class="nav-item nav-item-this"><a href="">Python Development Mode</a></li>190                <li class="right">191                    192 193    <div class="inline-search" role="search">194        <form class="inline-search" action="../search.html" method="get">195          <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box">196          <input type="submit" value="Go">197        </form>198    </div>199                     |200                </li>201            <li class="right">202<label class="theme-selector-label">203    Theme204    <select class="theme-selector" oninput="activateTheme(this.value)">205        <option value="auto" selected>Auto</option>206        <option value="light">Light</option>207        <option value="dark">Dark</option>208    </select>209</label> |</li>210            211      </ul>212    </div>    213 214    <div class="document">215      <div class="documentwrapper">216        <div class="bodywrapper">217          <div class="body" role="main">218            219  <section id="python-development-mode">220<span id="devmode"></span><h1>Python Development Mode<a class="headerlink" href="#python-development-mode" title="Link to this heading">¶</a></h1>221<div class="versionadded">222<p><span class="versionmodified added">Added in version 3.7.</span></p>223</div>224<p>The Python Development Mode introduces additional runtime checks that are too225expensive to be enabled by default. It should not be more verbose than the226default if the code is correct; new warnings are only emitted when an issue is227detected.</p>228<p>It can be enabled using the <a class="reference internal" href="../using/cmdline.html#cmdoption-X"><code class="xref std std-option docutils literal notranslate"><span class="pre">-X</span> <span class="pre">dev</span></code></a> command line option or by229setting the <span class="target" id="index-0"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONDEVMODE"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONDEVMODE</span></code></a> environment variable to <code class="docutils literal notranslate"><span class="pre">1</span></code>.</p>230<p>See also <a class="reference internal" href="../using/configure.html#debug-build"><span class="std std-ref">Python debug build</span></a>.</p>231<section id="effects-of-the-python-development-mode">232<h2>Effects of the Python Development Mode<a class="headerlink" href="#effects-of-the-python-development-mode" title="Link to this heading">¶</a></h2>233<p>Enabling the Python Development Mode is similar to the following command, but234with additional effects described below:</p>235<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">PYTHONMALLOC</span><span class="o">=</span><span class="n">debug</span> <span class="n">PYTHONASYNCIODEBUG</span><span class="o">=</span><span class="mi">1</span> <span class="n">python</span> <span class="o">-</span><span class="n">W</span> <span class="n">default</span> <span class="o">-</span><span class="n">X</span> <span class="n">faulthandler</span>236</pre></div>237</div>238<p>Effects of the Python Development Mode:</p>239<ul>240<li><p>Add <code class="docutils literal notranslate"><span class="pre">default</span></code> <a class="reference internal" href="warnings.html#describing-warning-filters"><span class="std std-ref">warning filter</span></a>. The241following warnings are shown:</p>242<ul class="simple">243<li><p><a class="reference internal" href="exceptions.html#DeprecationWarning" title="DeprecationWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">DeprecationWarning</span></code></a></p></li>244<li><p><a class="reference internal" href="exceptions.html#ImportWarning" title="ImportWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImportWarning</span></code></a></p></li>245<li><p><a class="reference internal" href="exceptions.html#PendingDeprecationWarning" title="PendingDeprecationWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">PendingDeprecationWarning</span></code></a></p></li>246<li><p><a class="reference internal" href="exceptions.html#ResourceWarning" title="ResourceWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ResourceWarning</span></code></a></p></li>247</ul>248<p>Normally, the above warnings are filtered by the default <a class="reference internal" href="warnings.html#describing-warning-filters"><span class="std std-ref">warning249filters</span></a>.</p>250<p>It behaves as if the <a class="reference internal" href="../using/cmdline.html#cmdoption-W"><code class="xref std std-option docutils literal notranslate"><span class="pre">-W</span> <span class="pre">default</span></code></a> command line option is used.</p>251<p>Use the <a class="reference internal" href="../using/cmdline.html#cmdoption-W"><code class="xref std std-option docutils literal notranslate"><span class="pre">-W</span> <span class="pre">error</span></code></a> command line option or set the252<span class="target" id="index-1"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONWARNINGS"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONWARNINGS</span></code></a> environment variable to <code class="docutils literal notranslate"><span class="pre">error</span></code> to treat warnings253as errors.</p>254</li>255<li><p>Install debug hooks on memory allocators to check for:</p>256<ul class="simple">257<li><p>Buffer underflow</p></li>258<li><p>Buffer overflow</p></li>259<li><p>Memory allocator API violation</p></li>260<li><p>Unsafe usage of the GIL</p></li>261</ul>262<p>See the <a class="reference internal" href="../c-api/memory.html#c.PyMem_SetupDebugHooks" title="PyMem_SetupDebugHooks"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyMem_SetupDebugHooks()</span></code></a> C function.</p>263<p>It behaves as if the <span class="target" id="index-2"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONMALLOC"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONMALLOC</span></code></a> environment variable is set to264<code class="docutils literal notranslate"><span class="pre">debug</span></code>.</p>265<p>To enable the Python Development Mode without installing debug hooks on266memory allocators, set the <span class="target" id="index-3"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONMALLOC"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONMALLOC</span></code></a> environment variable to267<code class="docutils literal notranslate"><span class="pre">default</span></code>.</p>268</li>269<li><p>Call <a class="reference internal" href="faulthandler.html#faulthandler.enable" title="faulthandler.enable"><code class="xref py py-func docutils literal notranslate"><span class="pre">faulthandler.enable()</span></code></a> at Python startup to install handlers for270the <a class="reference internal" href="signal.html#signal.SIGSEGV" title="signal.SIGSEGV"><code class="xref py py-const docutils literal notranslate"><span class="pre">SIGSEGV</span></code></a>, <a class="reference internal" href="signal.html#signal.SIGFPE" title="signal.SIGFPE"><code class="xref py py-const docutils literal notranslate"><span class="pre">SIGFPE</span></code></a>,271<a class="reference internal" href="signal.html#signal.SIGABRT" title="signal.SIGABRT"><code class="xref py py-const docutils literal notranslate"><span class="pre">SIGABRT</span></code></a>, <a class="reference internal" href="signal.html#signal.SIGBUS" title="signal.SIGBUS"><code class="xref py py-const docutils literal notranslate"><span class="pre">SIGBUS</span></code></a> and272<a class="reference internal" href="signal.html#signal.SIGILL" title="signal.SIGILL"><code class="xref py py-const docutils literal notranslate"><span class="pre">SIGILL</span></code></a> signals to dump the Python traceback on a crash.</p>273<p>It behaves as if the <a class="reference internal" href="../using/cmdline.html#cmdoption-X"><code class="xref std std-option docutils literal notranslate"><span class="pre">-X</span> <span class="pre">faulthandler</span></code></a> command line option is274used or if the <span class="target" id="index-4"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONFAULTHANDLER"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONFAULTHANDLER</span></code></a> environment variable is set to275<code class="docutils literal notranslate"><span class="pre">1</span></code>.</p>276</li>277<li><p>Enable <a class="reference internal" href="asyncio-dev.html#asyncio-debug-mode"><span class="std std-ref">asyncio debug mode</span></a>. For example,278<a class="reference internal" href="asyncio.html#module-asyncio" title="asyncio: Asynchronous I/O."><code class="xref py py-mod docutils literal notranslate"><span class="pre">asyncio</span></code></a> checks for coroutines that were not awaited and logs them.</p>279<p>It behaves as if the <span class="target" id="index-5"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONASYNCIODEBUG"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONASYNCIODEBUG</span></code></a> environment variable is set280to <code class="docutils literal notranslate"><span class="pre">1</span></code>.</p>281</li>282<li><p>Check the <em>encoding</em> and <em>errors</em> arguments for string encoding and decoding283operations. Examples: <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a>, <a class="reference internal" href="stdtypes.html#str.encode" title="str.encode"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.encode()</span></code></a> and284<a class="reference internal" href="stdtypes.html#bytes.decode" title="bytes.decode"><code class="xref py py-meth docutils literal notranslate"><span class="pre">bytes.decode()</span></code></a>.</p>285<p>By default, for best performance, the <em>errors</em> argument is only checked at286the first encoding/decoding error and the <em>encoding</em> argument is sometimes287ignored for empty strings.</p>288</li>289<li><p>The <a class="reference internal" href="io.html#io.IOBase" title="io.IOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">io.IOBase</span></code></a> destructor logs <code class="docutils literal notranslate"><span class="pre">close()</span></code> exceptions.</p></li>290<li><p>Set the <a class="reference internal" href="sys.html#sys.flags.dev_mode" title="sys.flags.dev_mode"><code class="xref py py-attr docutils literal notranslate"><span class="pre">dev_mode</span></code></a> attribute of <a class="reference internal" href="sys.html#sys.flags" title="sys.flags"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.flags</span></code></a> to291<code class="docutils literal notranslate"><span class="pre">True</span></code>.</p></li>292</ul>293<p>The Python Development Mode does not enable the <a class="reference internal" href="tracemalloc.html#module-tracemalloc" title="tracemalloc: Trace memory allocations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">tracemalloc</span></code></a> module by294default, because the overhead cost (to performance and memory) would be too295large. Enabling the <code class="xref py py-mod docutils literal notranslate"><span class="pre">tracemalloc</span></code> module provides additional information296on the origin of some errors. For example, <a class="reference internal" href="exceptions.html#ResourceWarning" title="ResourceWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ResourceWarning</span></code></a> logs the297traceback where the resource was allocated, and a buffer overflow error logs298the traceback where the memory block was allocated.</p>299<p>The Python Development Mode does not prevent the <a class="reference internal" href="../using/cmdline.html#cmdoption-O"><code class="xref std std-option docutils literal notranslate"><span class="pre">-O</span></code></a> command line300option from removing <a class="reference internal" href="../reference/simple_stmts.html#assert"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">assert</span></code></a> statements nor from setting301<a class="reference internal" href="constants.html#debug__" title="__debug__"><code class="xref py py-const docutils literal notranslate"><span class="pre">__debug__</span></code></a> to <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>302<p>The Python Development Mode can only be enabled at the Python startup. Its303value can be read from <a class="reference internal" href="sys.html#sys.flags" title="sys.flags"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.flags.dev_mode</span></code></a>.</p>304<div class="versionchanged">305<p><span class="versionmodified changed">Changed in version 3.8: </span>The <a class="reference internal" href="io.html#io.IOBase" title="io.IOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">io.IOBase</span></code></a> destructor now logs <code class="docutils literal notranslate"><span class="pre">close()</span></code> exceptions.</p>306</div>307<div class="versionchanged">308<p><span class="versionmodified changed">Changed in version 3.9: </span>The <em>encoding</em> and <em>errors</em> arguments are now checked for string encoding309and decoding operations.</p>310</div>311</section>312<section id="resourcewarning-example">313<h2>ResourceWarning Example<a class="headerlink" href="#resourcewarning-example" title="Link to this heading">¶</a></h2>314<p>Example of a script counting the number of lines of the text file specified in315the command line:</p>316<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span><span class="w"> </span><span class="nn">sys</span>317 318<span class="k">def</span><span class="w"> </span><span class="nf">main</span><span class="p">():</span>319    <span class="n">fp</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">[</span><span class="mi">1</span><span class="p">])</span>320    <span class="n">nlines</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="n">fp</span><span class="o">.</span><span class="n">readlines</span><span class="p">())</span>321    <span class="nb">print</span><span class="p">(</span><span class="n">nlines</span><span class="p">)</span>322    <span class="c1"># The file is closed implicitly</span>323 324<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s2">&quot;__main__&quot;</span><span class="p">:</span>325    <span class="n">main</span><span class="p">()</span>326</pre></div>327</div>328<p>The script does not close the file explicitly. By default, Python does not emit329any warning. Example using README.txt, which has 269 lines:</p>330<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span>python<span class="w"> </span>script.py<span class="w"> </span>README.txt331<span class="go">269</span>332</pre></div>333</div>334<p>Enabling the Python Development Mode displays a <a class="reference internal" href="exceptions.html#ResourceWarning" title="ResourceWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ResourceWarning</span></code></a> warning:</p>335<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span>python<span class="w"> </span>-X<span class="w"> </span>dev<span class="w"> </span>script.py<span class="w"> </span>README.txt336<span class="go">269</span>337<span class="go">script.py:10: ResourceWarning: unclosed file &lt;_io.TextIOWrapper name=&#39;README.rst&#39; mode=&#39;r&#39; encoding=&#39;UTF-8&#39;&gt;</span>338<span class="go">  main()</span>339<span class="go">ResourceWarning: Enable tracemalloc to get the object allocation traceback</span>340</pre></div>341</div>342<p>In addition, enabling <a class="reference internal" href="tracemalloc.html#module-tracemalloc" title="tracemalloc: Trace memory allocations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">tracemalloc</span></code></a> shows the line where the file was343opened:</p>344<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span>python<span class="w"> </span>-X<span class="w"> </span>dev<span class="w"> </span>-X<span class="w"> </span><span class="nv">tracemalloc</span><span class="o">=</span><span class="m">5</span><span class="w"> </span>script.py<span class="w"> </span>README.rst345<span class="go">269</span>346<span class="go">script.py:10: ResourceWarning: unclosed file &lt;_io.TextIOWrapper name=&#39;README.rst&#39; mode=&#39;r&#39; encoding=&#39;UTF-8&#39;&gt;</span>347<span class="go">  main()</span>348<span class="go">Object allocated at (most recent call last):</span>349<span class="go">  File &quot;script.py&quot;, lineno 10</span>350<span class="go">    main()</span>351<span class="go">  File &quot;script.py&quot;, lineno 4</span>352<span class="go">    fp = open(sys.argv[1])</span>353</pre></div>354</div>355<p>The fix is to close explicitly the file. Example using a context manager:</p>356<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span><span class="w"> </span><span class="nf">main</span><span class="p">():</span>357    <span class="c1"># Close the file explicitly when exiting the with block</span>358    <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">[</span><span class="mi">1</span><span class="p">])</span> <span class="k">as</span> <span class="n">fp</span><span class="p">:</span>359        <span class="n">nlines</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="n">fp</span><span class="o">.</span><span class="n">readlines</span><span class="p">())</span>360    <span class="nb">print</span><span class="p">(</span><span class="n">nlines</span><span class="p">)</span>361</pre></div>362</div>363<p>Not closing a resource explicitly can leave a resource open for way longer than364expected; it can cause severe issues upon exiting Python. It is bad in365CPython, but it is even worse in PyPy. Closing resources explicitly makes an366application more deterministic and more reliable.</p>367</section>368<section id="bad-file-descriptor-error-example">369<h2>Bad file descriptor error example<a class="headerlink" href="#bad-file-descriptor-error-example" title="Link to this heading">¶</a></h2>370<p>Script displaying the first line of itself:</p>371<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span><span class="w"> </span><span class="nn">os</span>372 373<span class="k">def</span><span class="w"> </span><span class="nf">main</span><span class="p">():</span>374    <span class="n">fp</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="vm">__file__</span><span class="p">)</span>375    <span class="n">firstline</span> <span class="o">=</span> <span class="n">fp</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>376    <span class="nb">print</span><span class="p">(</span><span class="n">firstline</span><span class="o">.</span><span class="n">rstrip</span><span class="p">())</span>377    <span class="n">os</span><span class="o">.</span><span class="n">close</span><span class="p">(</span><span class="n">fp</span><span class="o">.</span><span class="n">fileno</span><span class="p">())</span>378    <span class="c1"># The file is closed implicitly</span>379 380<span class="n">main</span><span class="p">()</span>381</pre></div>382</div>383<p>By default, Python does not emit any warning:</p>384<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span>python<span class="w"> </span>script.py385<span class="go">import os</span>386</pre></div>387</div>388<p>The Python Development Mode shows a <a class="reference internal" href="exceptions.html#ResourceWarning" title="ResourceWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ResourceWarning</span></code></a> and logs a “Bad file389descriptor” error when finalizing the file object:</p>390<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span>python<span class="w"> </span>-X<span class="w"> </span>dev<span class="w"> </span>script.py391<span class="go">import os</span>392<span class="go">script.py:10: ResourceWarning: unclosed file &lt;_io.TextIOWrapper name=&#39;script.py&#39; mode=&#39;r&#39; encoding=&#39;UTF-8&#39;&gt;</span>393<span class="go">  main()</span>394<span class="go">ResourceWarning: Enable tracemalloc to get the object allocation traceback</span>395<span class="go">Exception ignored in: &lt;_io.TextIOWrapper name=&#39;script.py&#39; mode=&#39;r&#39; encoding=&#39;UTF-8&#39;&gt;</span>396<span class="go">Traceback (most recent call last):</span>397<span class="go">  File &quot;script.py&quot;, line 10, in &lt;module&gt;</span>398<span class="go">    main()</span>399<span class="go">OSError: [Errno 9] Bad file descriptor</span>400</pre></div>401</div>402<p><code class="docutils literal notranslate"><span class="pre">os.close(fp.fileno())</span></code> closes the file descriptor. When the file object403finalizer tries to close the file descriptor again, it fails with the <code class="docutils literal notranslate"><span class="pre">Bad</span>404<span class="pre">file</span> <span class="pre">descriptor</span></code> error. A file descriptor must be closed only once. In the405worst case scenario, closing it twice can lead to a crash (see <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=18748">bpo-18748</a>406for an example).</p>407<p>The fix is to remove the <code class="docutils literal notranslate"><span class="pre">os.close(fp.fileno())</span></code> line, or open the file with408<code class="docutils literal notranslate"><span class="pre">closefd=False</span></code>.</p>409</section>410</section>411 412 413            <div class="clearer"></div>414          </div>415        </div>416      </div>417      <div class="sphinxsidebar" role="navigation" aria-label="Main">418        <div class="sphinxsidebarwrapper">419  <div>420    <h3><a href="../contents.html">Table of Contents</a></h3>421    <ul>422<li><a class="reference internal" href="#">Python Development Mode</a><ul>423<li><a class="reference internal" href="#effects-of-the-python-development-mode">Effects of the Python Development Mode</a></li>424<li><a class="reference internal" href="#resourcewarning-example">ResourceWarning Example</a></li>425<li><a class="reference internal" href="#bad-file-descriptor-error-example">Bad file descriptor error example</a></li>426</ul>427</li>428</ul>429 430  </div>431  <div>432    <h4>Previous topic</h4>433    <p class="topless"><a href="pydoc.html"434                          title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">pydoc</span></code> — Documentation generator and online help system</a></p>435  </div>436  <div>437    <h4>Next topic</h4>438    <p class="topless"><a href="doctest.html"439                          title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code> — Test interactive Python examples</a></p>440  </div>441  <script>442    document.addEventListener('DOMContentLoaded', () => {443        const title = document.querySelector('meta[property="og:title"]').content;444        const elements = document.querySelectorAll('.improvepage');445        const pageurl = window.location.href.split('?')[0];446        elements.forEach(element => {447            const url = new URL(element.href.split('?')[0].replace("-nojs", ""));448            url.searchParams.set('pagetitle', title);449            url.searchParams.set('pageurl', pageurl);450            url.searchParams.set('pagesource', "library/devmode.rst");451            element.href = url.toString();452        });453    });454  </script>455  <div role="note" aria-label="source link">456    <h3>This page</h3>457    <ul class="this-page-menu">458      <li><a href="../bugs.html">Report a bug</a></li>459      <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li>460      <li>461        <a href="https://github.com/python/cpython/blob/main/Doc/library/devmode.rst?plain=1"462            rel="nofollow">Show source463        </a>464      </li>465      466    </ul>467  </div>468        </div>469<div id="sidebarbutton" title="Collapse sidebar">470<span>«</span>471</div>472 473      </div>474      <div class="clearer"></div>475    </div>  476    <div class="related" role="navigation" aria-label="Related">477      <h3>Navigation</h3>478      <ul>479        <li class="right" style="margin-right: 10px">480          <a href="../genindex.html" title="General Index"481             >index</a></li>482        <li class="right" >483          <a href="../py-modindex.html" title="Python Module Index"484             >modules</a> |</li>485        <li class="right" >486          <a href="doctest.html" title="doctest — Test interactive Python examples"487             >next</a> |</li>488        <li class="right" >489          <a href="pydoc.html" title="pydoc — Documentation generator and online help system"490             >previous</a> |</li>491 492          <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li>493          <li><a href="https://www.python.org/">Python</a> &#187;</li>494          <li class="switchers">495            <div class="language_switcher_placeholder"></div>496            <div class="version_switcher_placeholder"></div>497          </li>498          <li>499              500          </li>501    <li id="cpython-language-and-version">502      <a href="../index.html">3.15.0a6 Documentation</a> &#187;503    </li>504 505          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>506          <li class="nav-item nav-item-2"><a href="development.html" >Development Tools</a> &#187;</li>507        <li class="nav-item nav-item-this"><a href="">Python Development Mode</a></li>508                <li class="right">509                    510 511    <div class="inline-search" role="search">512        <form class="inline-search" action="../search.html" method="get">513          <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box">514          <input type="submit" value="Go">515        </form>516    </div>517                     |518                </li>519            <li class="right">520<label class="theme-selector-label">521    Theme522    <select class="theme-selector" oninput="activateTheme(this.value)">523        <option value="auto" selected>Auto</option>524        <option value="light">Light</option>525        <option value="dark">Dark</option>526    </select>527</label> |</li>528            529      </ul>530    </div>  531    <div class="footer">532    &copy; <a href="../copyright.html">Copyright</a> 2001 Python Software Foundation.533    <br>534    This page is licensed under the Python Software Foundation License Version 2.535    <br>536    Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.537    <br>538    539      See <a href="/license.html">History and License</a> for more information.<br>540    541    542    <br>543 544    The Python Software Foundation is a non-profit corporation.545<a href="https://www.python.org/psf/donations/">Please donate.</a>546<br>547    <br>548      Last updated on Mar 10, 2026 (08:58 UTC).549    550      <a href="/bugs.html">Found a bug</a>?551    552    <br>553 554    Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3.555    </div>556 557  </body>558</html>