Team Ai
Apppublic

parthtamu/rag-code-assistant

sourceHugging Faceupdated 7mo agoView on Hugging Face
0likes
warnings.html1053 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="warnings — Warning control" />8<meta property="og:type" content="website" />9<meta property="og:url" content="https://docs.python.org/3/library/warnings.html" />10<meta property="og:site_name" content="Python documentation" />11<meta property="og:description" content="Source code: Lib/warnings.py Warning messages are typically issued in situations where it is useful to alert the user of some condition in a program, where that condition (normally) doesn’t warrant..." />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_warnings_756dba17.png" />15<meta property="og:image:alt" content="Source code: Lib/warnings.py Warning messages are typically issued in situations where it is useful to alert the user of some condition in a program, where that condition (normally) doesn’t warrant..." />16<meta name="description" content="Source code: Lib/warnings.py Warning messages are typically issued in situations where it is useful to alert the user of some condition in a program, where that condition (normally) doesn’t warrant..." />17<meta name="twitter:card" content="summary_large_image" />18<meta name="theme-color" content="#3776ab">19 20    <title>warnings — Warning control &#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="dataclasses — Data Classes" href="dataclasses.html" />43    <link rel="prev" title="__main__ — Top-level code environment" href="__main__.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/warnings.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="#"><code class="xref py py-mod docutils literal notranslate"><span class="pre">warnings</span></code> — Warning control</a><ul>108<li><a class="reference internal" href="#warning-categories">Warning Categories</a></li>109<li><a class="reference internal" href="#the-warnings-filter">The Warnings Filter</a><ul>110<li><a class="reference internal" href="#repeated-warning-suppression-criteria">Repeated Warning Suppression Criteria</a></li>111<li><a class="reference internal" href="#describing-warning-filters">Describing Warning Filters</a></li>112<li><a class="reference internal" href="#default-warning-filter">Default Warning Filter</a></li>113<li><a class="reference internal" href="#overriding-the-default-filter">Overriding the default filter</a></li>114</ul>115</li>116<li><a class="reference internal" href="#temporarily-suppressing-warnings">Temporarily Suppressing Warnings</a></li>117<li><a class="reference internal" href="#testing-warnings">Testing Warnings</a></li>118<li><a class="reference internal" href="#updating-code-for-new-versions-of-dependencies">Updating Code For New Versions of Dependencies</a></li>119<li><a class="reference internal" href="#available-functions">Available Functions</a></li>120<li><a class="reference internal" href="#available-context-managers">Available Context Managers</a></li>121<li><a class="reference internal" href="#concurrent-safety-of-context-managers">Concurrent safety of Context Managers</a></li>122</ul>123</li>124</ul>125 126  </div>127  <div>128    <h4>Previous topic</h4>129    <p class="topless"><a href="__main__.html"130                          title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">__main__</span></code> — Top-level code environment</a></p>131  </div>132  <div>133    <h4>Next topic</h4>134    <p class="topless"><a href="dataclasses.html"135                          title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">dataclasses</span></code> — Data Classes</a></p>136  </div>137  <script>138    document.addEventListener('DOMContentLoaded', () => {139        const title = document.querySelector('meta[property="og:title"]').content;140        const elements = document.querySelectorAll('.improvepage');141        const pageurl = window.location.href.split('?')[0];142        elements.forEach(element => {143            const url = new URL(element.href.split('?')[0].replace("-nojs", ""));144            url.searchParams.set('pagetitle', title);145            url.searchParams.set('pageurl', pageurl);146            url.searchParams.set('pagesource', "library/warnings.rst");147            element.href = url.toString();148        });149    });150  </script>151  <div role="note" aria-label="source link">152    <h3>This page</h3>153    <ul class="this-page-menu">154      <li><a href="../bugs.html">Report a bug</a></li>155      <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li>156      <li>157        <a href="https://github.com/python/cpython/blob/main/Doc/library/warnings.rst?plain=1"158            rel="nofollow">Show source159        </a>160      </li>161      162    </ul>163  </div>164        </nav>165    </div>166</div>167 168  169    <div class="related" role="navigation" aria-label="Related">170      <h3>Navigation</h3>171      <ul>172        <li class="right" style="margin-right: 10px">173          <a href="../genindex.html" title="General Index"174             accesskey="I">index</a></li>175        <li class="right" >176          <a href="../py-modindex.html" title="Python Module Index"177             >modules</a> |</li>178        <li class="right" >179          <a href="dataclasses.html" title="dataclasses — Data Classes"180             accesskey="N">next</a> |</li>181        <li class="right" >182          <a href="__main__.html" title="__main__ — Top-level code environment"183             accesskey="P">previous</a> |</li>184 185          <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li>186          <li><a href="https://www.python.org/">Python</a> &#187;</li>187          <li class="switchers">188            <div class="language_switcher_placeholder"></div>189            <div class="version_switcher_placeholder"></div>190          </li>191          <li>192              193          </li>194    <li id="cpython-language-and-version">195      <a href="../index.html">3.15.0a6 Documentation</a> &#187;196    </li>197 198          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>199          <li class="nav-item nav-item-2"><a href="python.html" accesskey="U">Python Runtime Services</a> &#187;</li>200        <li class="nav-item nav-item-this"><a href=""><code class="xref py py-mod docutils literal notranslate"><span class="pre">warnings</span></code> — Warning control</a></li>201                <li class="right">202                    203 204    <div class="inline-search" role="search">205        <form class="inline-search" action="../search.html" method="get">206          <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box">207          <input type="submit" value="Go">208        </form>209    </div>210                     |211                </li>212            <li class="right">213<label class="theme-selector-label">214    Theme215    <select class="theme-selector" oninput="activateTheme(this.value)">216        <option value="auto" selected>Auto</option>217        <option value="light">Light</option>218        <option value="dark">Dark</option>219    </select>220</label> |</li>221            222      </ul>223    </div>    224 225    <div class="document">226      <div class="documentwrapper">227        <div class="bodywrapper">228          <div class="body" role="main">229            230  <section id="module-warnings">231<span id="warnings-warning-control"></span><h1><code class="xref py py-mod docutils literal notranslate"><span class="pre">warnings</span></code> — Warning control<a class="headerlink" href="#module-warnings" title="Link to this heading">¶</a></h1>232<p><strong>Source code:</strong> <a class="extlink-source reference external" href="https://github.com/python/cpython/tree/main/Lib/warnings.py">Lib/warnings.py</a></p>233<hr class="docutils" id="index-0" />234<p>Warning messages are typically issued in situations where it is useful to alert235the user of some condition in a program, where that condition (normally) doesn’t236warrant raising an exception and terminating the program.  For example, one237might want to issue a warning when a program uses an obsolete module.</p>238<p>Python programmers issue warnings by calling the <a class="reference internal" href="#warnings.warn" title="warnings.warn"><code class="xref py py-func docutils literal notranslate"><span class="pre">warn()</span></code></a> function defined239in this module.  (C programmers use <a class="reference internal" href="../c-api/exceptions.html#c.PyErr_WarnEx" title="PyErr_WarnEx"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_WarnEx()</span></code></a>; see240<a class="reference internal" href="../c-api/exceptions.html#exceptionhandling"><span class="std std-ref">Exception Handling</span></a> for details).</p>241<p>Warning messages are normally written to <a class="reference internal" href="sys.html#sys.stderr" title="sys.stderr"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.stderr</span></code></a>, but their disposition242can be changed flexibly, from ignoring all warnings to turning them into243exceptions.  The disposition of warnings can vary based on the <a class="reference internal" href="#warning-categories"><span class="std std-ref">warning category</span></a>, the text of the warning message, and the source location where it244is issued.  Repetitions of a particular warning for the same source location are245typically suppressed.</p>246<p>There are two stages in warning control: first, each time a warning is issued, a247determination is made whether a message should be issued or not; next, if a248message is to be issued, it is formatted and printed using a user-settable hook.</p>249<p>The determination whether to issue a warning message is controlled by the250<a class="reference internal" href="#warning-filter"><span class="std std-ref">warning filter</span></a>, which is a sequence of matching rules and actions. Rules can be251added to the filter by calling <a class="reference internal" href="#warnings.filterwarnings" title="warnings.filterwarnings"><code class="xref py py-func docutils literal notranslate"><span class="pre">filterwarnings()</span></code></a> and reset to its default252state by calling <a class="reference internal" href="#warnings.resetwarnings" title="warnings.resetwarnings"><code class="xref py py-func docutils literal notranslate"><span class="pre">resetwarnings()</span></code></a>.</p>253<p>The printing of warning messages is done by calling <a class="reference internal" href="#warnings.showwarning" title="warnings.showwarning"><code class="xref py py-func docutils literal notranslate"><span class="pre">showwarning()</span></code></a>, which254may be overridden; the default implementation of this function formats the255message by calling <a class="reference internal" href="#warnings.formatwarning" title="warnings.formatwarning"><code class="xref py py-func docutils literal notranslate"><span class="pre">formatwarning()</span></code></a>, which is also available for use by256custom implementations.</p>257<div class="admonition seealso">258<p class="admonition-title">See also</p>259<p><a class="reference internal" href="logging.html#logging.captureWarnings" title="logging.captureWarnings"><code class="xref py py-func docutils literal notranslate"><span class="pre">logging.captureWarnings()</span></code></a> allows you to handle all warnings with260the standard logging infrastructure.</p>261</div>262<section id="warning-categories">263<span id="id1"></span><h2>Warning Categories<a class="headerlink" href="#warning-categories" title="Link to this heading">¶</a></h2>264<p>There are a number of built-in exceptions that represent warning categories.265This categorization is useful to be able to filter out groups of warnings.</p>266<p>While these are technically267<a class="reference internal" href="exceptions.html#warning-categories-as-exceptions"><span class="std std-ref">built-in exceptions</span></a>, they are268documented here, because conceptually they belong to the warnings mechanism.</p>269<p>User code can define additional warning categories by subclassing one of the270standard warning categories.  A warning category must always be a subclass of271the <a class="reference internal" href="exceptions.html#Warning" title="Warning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Warning</span></code></a> class.</p>272<p>The following warnings category classes are currently defined:</p>273<table class="docutils align-default">274<thead>275<tr class="row-odd"><th class="head"><p>Class</p></th>276<th class="head"><p>Description</p></th>277</tr>278</thead>279<tbody>280<tr class="row-even"><td><p><a class="reference internal" href="exceptions.html#Warning" title="Warning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Warning</span></code></a></p></td>281<td><p>This is the base class of all warning282category classes.  It is a subclass of283<a class="reference internal" href="exceptions.html#Exception" title="Exception"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Exception</span></code></a>.</p></td>284</tr>285<tr class="row-odd"><td><p><a class="reference internal" href="exceptions.html#UserWarning" title="UserWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UserWarning</span></code></a></p></td>286<td><p>The default category for <a class="reference internal" href="#warnings.warn" title="warnings.warn"><code class="xref py py-func docutils literal notranslate"><span class="pre">warn()</span></code></a>.</p></td>287</tr>288<tr class="row-even"><td><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></td>289<td><p>Base category for warnings about deprecated290features when those warnings are intended for291other Python developers (ignored by default,292unless triggered by code in <code class="docutils literal notranslate"><span class="pre">__main__</span></code>).</p></td>293</tr>294<tr class="row-odd"><td><p><a class="reference internal" href="exceptions.html#SyntaxWarning" title="SyntaxWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxWarning</span></code></a></p></td>295<td><p>Base category for warnings about dubious296syntactic features (typically emitted when297compiling Python source code, and hence298may not be suppressed by runtime filters)</p></td>299</tr>300<tr class="row-even"><td><p><a class="reference internal" href="exceptions.html#RuntimeWarning" title="RuntimeWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeWarning</span></code></a></p></td>301<td><p>Base category for warnings about dubious302runtime features.</p></td>303</tr>304<tr class="row-odd"><td><p><a class="reference internal" href="exceptions.html#FutureWarning" title="FutureWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">FutureWarning</span></code></a></p></td>305<td><p>Base category for warnings about deprecated306features when those warnings are intended for307end users of applications that are written in308Python.</p></td>309</tr>310<tr class="row-even"><td><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></td>311<td><p>Base category for warnings about features312that will be deprecated in the future313(ignored by default).</p></td>314</tr>315<tr class="row-odd"><td><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></td>316<td><p>Base category for warnings triggered during317the process of importing a module (ignored by318default).</p></td>319</tr>320<tr class="row-even"><td><p><a class="reference internal" href="exceptions.html#UnicodeWarning" title="UnicodeWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeWarning</span></code></a></p></td>321<td><p>Base category for warnings related to322Unicode.</p></td>323</tr>324<tr class="row-odd"><td><p><a class="reference internal" href="exceptions.html#BytesWarning" title="BytesWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">BytesWarning</span></code></a></p></td>325<td><p>Base category for warnings related to326<a class="reference internal" href="stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> and <a class="reference internal" href="stdtypes.html#bytearray" title="bytearray"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytearray</span></code></a>.</p></td>327</tr>328<tr class="row-even"><td><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></td>329<td><p>Base category for warnings related to330resource usage (ignored by default).</p></td>331</tr>332</tbody>333</table>334<div class="versionchanged">335<p><span class="versionmodified changed">Changed in version 3.7: </span>Previously <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> and <a class="reference internal" href="exceptions.html#FutureWarning" title="FutureWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">FutureWarning</span></code></a> were336distinguished based on whether a feature was being removed entirely or337changing its behaviour. They are now distinguished based on their338intended audience and the way they’re handled by the default warnings339filters.</p>340</div>341</section>342<section id="the-warnings-filter">343<span id="warning-filter"></span><h2>The Warnings Filter<a class="headerlink" href="#the-warnings-filter" title="Link to this heading">¶</a></h2>344<p>The warnings filter controls whether warnings are ignored, displayed, or turned345into errors (raising an exception).</p>346<p>Conceptually, the warnings filter maintains an ordered list of filter347specifications; any specific warning is matched against each filter348specification in the list in turn until a match is found; the filter determines349the disposition of the match.  Each entry is a tuple of the form (<em>action</em>,350<em>message</em>, <em>category</em>, <em>module</em>, <em>lineno</em>), where:</p>351<ul>352<li><p><em>action</em> is one of the following strings:</p>353<table class="docutils align-default">354<thead>355<tr class="row-odd"><th class="head"><p>Value</p></th>356<th class="head"><p>Disposition</p></th>357</tr>358</thead>359<tbody>360<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">&quot;default&quot;</span></code></p></td>361<td><p>print the first occurrence of matching362warnings for each location (module +363line number) where the warning is issued</p></td>364</tr>365<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">&quot;error&quot;</span></code></p></td>366<td><p>turn matching warnings into exceptions</p></td>367</tr>368<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">&quot;ignore&quot;</span></code></p></td>369<td><p>never print matching warnings</p></td>370</tr>371<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">&quot;always&quot;</span></code></p></td>372<td><p>always print matching warnings</p></td>373</tr>374<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">&quot;all&quot;</span></code></p></td>375<td><p>alias to “always”</p></td>376</tr>377<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">&quot;module&quot;</span></code></p></td>378<td><p>print the first occurrence of matching379warnings for each module where the warning380is issued (regardless of line number)</p></td>381</tr>382<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">&quot;once&quot;</span></code></p></td>383<td><p>print only the first occurrence of matching384warnings, regardless of location</p></td>385</tr>386</tbody>387</table>388</li>389<li><p><em>message</em> is a string containing a regular expression that the start of390the warning message must match, case-insensitively.  In <a class="reference internal" href="../using/cmdline.html#cmdoption-W"><code class="xref std std-option docutils literal notranslate"><span class="pre">-W</span></code></a> and391<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>, if <em>message</em> starts and ends with a forward slash392(<code class="docutils literal notranslate"><span class="pre">/</span></code>), it specifies a regular expression as above;393otherwise it is a literal string that the start of the394warning message must match (case-insensitively), ignoring any whitespace at395the start or end of <em>message</em>.</p></li>396<li><p><em>category</em> is a class (a subclass of <a class="reference internal" href="exceptions.html#Warning" title="Warning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Warning</span></code></a>) of which the warning397category must be a subclass in order to match.</p></li>398<li><p><em>module</em> is a string containing a regular expression that the start of the399fully qualified module name must match, case-sensitively.  In <a class="reference internal" href="../using/cmdline.html#cmdoption-W"><code class="xref std std-option docutils literal notranslate"><span class="pre">-W</span></code></a> and400<span class="target" id="index-2"></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>, if <em>module</em> starts and ends with a forward slash401(<code class="docutils literal notranslate"><span class="pre">/</span></code>), it specifies a regular expression as above;402otherwise it is a literal string that the403fully qualified module name must be equal to (case-sensitively), ignoring any404whitespace at the start or end of <em>module</em>.</p></li>405<li><p><em>lineno</em> is an integer that the line number where the warning occurred must406match, or <code class="docutils literal notranslate"><span class="pre">0</span></code> to match all line numbers.</p></li>407</ul>408<p>Since the <a class="reference internal" href="exceptions.html#Warning" title="Warning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Warning</span></code></a> class is derived from the built-in <a class="reference internal" href="exceptions.html#Exception" title="Exception"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Exception</span></code></a>409class, to turn a warning into an error we simply raise <code class="docutils literal notranslate"><span class="pre">category(message)</span></code>.</p>410<p>If a warning is reported and doesn’t match any registered filter then the411“default” action is applied (hence its name).</p>412<section id="repeated-warning-suppression-criteria">413<span id="id2"></span><h3>Repeated Warning Suppression Criteria<a class="headerlink" href="#repeated-warning-suppression-criteria" title="Link to this heading">¶</a></h3>414<p>The filters that suppress repeated warnings apply the following criteria to determine if a warning is considered a repeat:</p>415<ul class="simple">416<li><p><code class="docutils literal notranslate"><span class="pre">&quot;default&quot;</span></code>: A warning is considered a repeat only if the (<em>message</em>, <em>category</em>, <em>module</em>, <em>lineno</em>) are all the same.</p></li>417<li><p><code class="docutils literal notranslate"><span class="pre">&quot;module&quot;</span></code>: A warning is considered a repeat if the (<em>message</em>, <em>category</em>, <em>module</em>) are the same, ignoring the line number.</p></li>418<li><p><code class="docutils literal notranslate"><span class="pre">&quot;once&quot;</span></code>: A warning is considered a repeat if the (<em>message</em>, <em>category</em>) are the same, ignoring the module and line number.</p></li>419</ul>420</section>421<section id="describing-warning-filters">422<span id="id3"></span><h3>Describing Warning Filters<a class="headerlink" href="#describing-warning-filters" title="Link to this heading">¶</a></h3>423<p>The warnings filter is initialized by <a class="reference internal" href="../using/cmdline.html#cmdoption-W"><code class="xref std std-option docutils literal notranslate"><span class="pre">-W</span></code></a> options passed to the Python424interpreter command line and the <span class="target" id="index-3"></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.425The interpreter saves the arguments for all supplied entries without426interpretation in <a class="reference internal" href="sys.html#sys.warnoptions" title="sys.warnoptions"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.warnoptions</span></code></a>; the <code class="xref py py-mod docutils literal notranslate"><span class="pre">warnings</span></code> module parses these427when it is first imported (invalid options are ignored, after printing a428message to <a class="reference internal" href="sys.html#sys.stderr" title="sys.stderr"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.stderr</span></code></a>).</p>429<p>Individual warnings filters are specified as a sequence of fields separated by430colons:</p>431<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">action</span><span class="p">:</span><span class="n">message</span><span class="p">:</span><span class="n">category</span><span class="p">:</span><span class="n">module</span><span class="p">:</span><span class="n">line</span>432</pre></div>433</div>434<p>The meaning of each of these fields is as described in <a class="reference internal" href="#warning-filter"><span class="std std-ref">The Warnings Filter</span></a>.435When listing multiple filters on a single line (as for436<span class="target" id="index-4"></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>), the individual filters are separated by commas and437the filters listed later take precedence over those listed before them (as438they’re applied left-to-right, and the most recently applied filters take439precedence over earlier ones).</p>440<p>Commonly used warning filters apply to either all warnings, warnings in a441particular category, or warnings raised by particular modules or packages.442Some examples:</p>443<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">default</span>                      <span class="c1"># Show all warnings (even those ignored by default)</span>444<span class="n">ignore</span>                       <span class="c1"># Ignore all warnings</span>445<span class="n">error</span>                        <span class="c1"># Convert all warnings to errors</span>446<span class="n">error</span><span class="p">::</span><span class="ne">ResourceWarning</span>       <span class="c1"># Treat ResourceWarning messages as errors</span>447<span class="n">default</span><span class="p">::</span><span class="ne">DeprecationWarning</span>  <span class="c1"># Show DeprecationWarning messages</span>448<span class="n">ignore</span><span class="p">,</span><span class="n">default</span><span class="p">:::</span><span class="n">mymodule</span>    <span class="c1"># Only report warnings triggered by &quot;mymodule&quot;</span>449<span class="n">error</span><span class="p">:::</span><span class="n">mymodule</span>             <span class="c1"># Convert warnings to errors in &quot;mymodule&quot;</span>450</pre></div>451</div>452</section>453<section id="default-warning-filter">454<span id="id4"></span><h3>Default Warning Filter<a class="headerlink" href="#default-warning-filter" title="Link to this heading">¶</a></h3>455<p>By default, Python installs several warning filters, which can be overridden by456the <a class="reference internal" href="../using/cmdline.html#cmdoption-W"><code class="xref std std-option docutils literal notranslate"><span class="pre">-W</span></code></a> command-line option, the <span class="target" id="index-5"></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> environment457variable and calls to <a class="reference internal" href="#warnings.filterwarnings" title="warnings.filterwarnings"><code class="xref py py-func docutils literal notranslate"><span class="pre">filterwarnings()</span></code></a>.</p>458<p>In regular release builds, the default warning filter has the following entries459(in order of precedence):</p>460<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">default</span><span class="p">::</span><span class="ne">DeprecationWarning</span><span class="p">:</span><span class="n">__main__</span>461<span class="n">ignore</span><span class="p">::</span><span class="ne">DeprecationWarning</span>462<span class="n">ignore</span><span class="p">::</span><span class="ne">PendingDeprecationWarning</span>463<span class="n">ignore</span><span class="p">::</span><span class="ne">ImportWarning</span>464<span class="n">ignore</span><span class="p">::</span><span class="ne">ResourceWarning</span>465</pre></div>466</div>467<p>In a <a class="reference internal" href="../using/configure.html#debug-build"><span class="std std-ref">debug build</span></a>, the list of default warning filters is empty.</p>468<div class="versionchanged">469<p><span class="versionmodified changed">Changed in version 3.2: </span><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> is now ignored by default in addition to470<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>471</div>472<div class="versionchanged">473<p><span class="versionmodified changed">Changed in version 3.7: </span><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> is once again shown by default when triggered474directly by code in <code class="docutils literal notranslate"><span class="pre">__main__</span></code>.</p>475</div>476<div class="versionchanged">477<p><span class="versionmodified changed">Changed in version 3.7: </span><a class="reference internal" href="exceptions.html#BytesWarning" title="BytesWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">BytesWarning</span></code></a> no longer appears in the default filter list and is478instead configured via <a class="reference internal" href="sys.html#sys.warnoptions" title="sys.warnoptions"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.warnoptions</span></code></a> when <a class="reference internal" href="../using/cmdline.html#cmdoption-b"><code class="xref std std-option docutils literal notranslate"><span class="pre">-b</span></code></a> is specified479twice.</p>480</div>481</section>482<section id="overriding-the-default-filter">483<span id="warning-disable"></span><h3>Overriding the default filter<a class="headerlink" href="#overriding-the-default-filter" title="Link to this heading">¶</a></h3>484<p>Developers of applications written in Python may wish to hide <em>all</em> Python level485warnings from their users by default, and only display them when running tests486or otherwise working on the application. The <a class="reference internal" href="sys.html#sys.warnoptions" title="sys.warnoptions"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.warnoptions</span></code></a> attribute487used to pass filter configurations to the interpreter can be used as a marker to488indicate whether or not warnings should be disabled:</p>489<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>490 491<span class="k">if</span> <span class="ow">not</span> <span class="n">sys</span><span class="o">.</span><span class="n">warnoptions</span><span class="p">:</span>492    <span class="kn">import</span><span class="w"> </span><span class="nn">warnings</span>493    <span class="n">warnings</span><span class="o">.</span><span class="n">simplefilter</span><span class="p">(</span><span class="s2">&quot;ignore&quot;</span><span class="p">)</span>494</pre></div>495</div>496<p>Developers of test runners for Python code are advised to instead ensure that497<em>all</em> warnings are displayed by default for the code under test, using code498like:</p>499<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>500 501<span class="k">if</span> <span class="ow">not</span> <span class="n">sys</span><span class="o">.</span><span class="n">warnoptions</span><span class="p">:</span>502    <span class="kn">import</span><span class="w"> </span><span class="nn">os</span><span class="o">,</span><span class="w"> </span><span class="nn">warnings</span>503    <span class="n">warnings</span><span class="o">.</span><span class="n">simplefilter</span><span class="p">(</span><span class="s2">&quot;default&quot;</span><span class="p">)</span> <span class="c1"># Change the filter in this process</span>504    <span class="n">os</span><span class="o">.</span><span class="n">environ</span><span class="p">[</span><span class="s2">&quot;PYTHONWARNINGS&quot;</span><span class="p">]</span> <span class="o">=</span> <span class="s2">&quot;default&quot;</span> <span class="c1"># Also affect subprocesses</span>505</pre></div>506</div>507<p>Finally, developers of interactive shells that run user code in a namespace508other than <code class="docutils literal notranslate"><span class="pre">__main__</span></code> are advised to ensure that <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>509messages are made visible by default, using code like the following (where510<code class="docutils literal notranslate"><span class="pre">user_ns</span></code> is the module used to execute code entered interactively):</p>511<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span><span class="w"> </span><span class="nn">warnings</span>512<span class="n">warnings</span><span class="o">.</span><span class="n">filterwarnings</span><span class="p">(</span><span class="s2">&quot;default&quot;</span><span class="p">,</span> <span class="n">category</span><span class="o">=</span><span class="ne">DeprecationWarning</span><span class="p">,</span>513                                   <span class="n">module</span><span class="o">=</span><span class="n">user_ns</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s2">&quot;__name__&quot;</span><span class="p">))</span>514</pre></div>515</div>516</section>517</section>518<section id="temporarily-suppressing-warnings">519<span id="warning-suppress"></span><h2>Temporarily Suppressing Warnings<a class="headerlink" href="#temporarily-suppressing-warnings" title="Link to this heading">¶</a></h2>520<p>If you are using code that you know will raise a warning, such as a deprecated521function, but do not want to see the warning (even when warnings have been522explicitly configured via the command line), then it is possible to suppress523the warning using the <a class="reference internal" href="#warnings.catch_warnings" title="warnings.catch_warnings"><code class="xref py py-class docutils literal notranslate"><span class="pre">catch_warnings</span></code></a> context manager:</p>524<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span><span class="w"> </span><span class="nn">warnings</span>525 526<span class="k">def</span><span class="w"> </span><span class="nf">fxn</span><span class="p">():</span>527    <span class="n">warnings</span><span class="o">.</span><span class="n">warn</span><span class="p">(</span><span class="s2">&quot;deprecated&quot;</span><span class="p">,</span> <span class="ne">DeprecationWarning</span><span class="p">)</span>528 529<span class="k">with</span> <span class="n">warnings</span><span class="o">.</span><span class="n">catch_warnings</span><span class="p">():</span>530    <span class="n">warnings</span><span class="o">.</span><span class="n">simplefilter</span><span class="p">(</span><span class="s2">&quot;ignore&quot;</span><span class="p">)</span>531    <span class="n">fxn</span><span class="p">()</span>532</pre></div>533</div>534<p>While within the context manager all warnings will simply be ignored. This535allows you to use known-deprecated code without having to see the warning while536not suppressing the warning for other code that might not be aware of its use537of deprecated code.</p>538<blockquote>539<div><div class="admonition note">540<p class="admonition-title">Note</p>541<p>See <a class="reference internal" href="#warning-concurrent-safe"><span class="std std-ref">Concurrent safety of Context Managers</span></a> for details on the542concurrency-safety of the <a class="reference internal" href="#warnings.catch_warnings" title="warnings.catch_warnings"><code class="xref py py-class docutils literal notranslate"><span class="pre">catch_warnings</span></code></a> context manager when543used in programs using multiple threads or async functions.</p>544</div>545</div></blockquote>546</section>547<section id="testing-warnings">548<span id="warning-testing"></span><h2>Testing Warnings<a class="headerlink" href="#testing-warnings" title="Link to this heading">¶</a></h2>549<p>To test warnings raised by code, use the <a class="reference internal" href="#warnings.catch_warnings" title="warnings.catch_warnings"><code class="xref py py-class docutils literal notranslate"><span class="pre">catch_warnings</span></code></a> context550manager. With it you can temporarily mutate the warnings filter to facilitate551your testing. For instance, do the following to capture all raised warnings to552check:</p>553<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span><span class="w"> </span><span class="nn">warnings</span>554 555<span class="k">def</span><span class="w"> </span><span class="nf">fxn</span><span class="p">():</span>556    <span class="n">warnings</span><span class="o">.</span><span class="n">warn</span><span class="p">(</span><span class="s2">&quot;deprecated&quot;</span><span class="p">,</span> <span class="ne">DeprecationWarning</span><span class="p">)</span>557 558<span class="k">with</span> <span class="n">warnings</span><span class="o">.</span><span class="n">catch_warnings</span><span class="p">(</span><span class="n">record</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span> <span class="k">as</span> <span class="n">w</span><span class="p">:</span>559    <span class="c1"># Cause all warnings to always be triggered.</span>560    <span class="n">warnings</span><span class="o">.</span><span class="n">simplefilter</span><span class="p">(</span><span class="s2">&quot;always&quot;</span><span class="p">)</span>561    <span class="c1"># Trigger a warning.</span>562    <span class="n">fxn</span><span class="p">()</span>563    <span class="c1"># Verify some things</span>564    <span class="k">assert</span> <span class="nb">len</span><span class="p">(</span><span class="n">w</span><span class="p">)</span> <span class="o">==</span> <span class="mi">1</span>565    <span class="k">assert</span> <span class="nb">issubclass</span><span class="p">(</span><span class="n">w</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span><span class="o">.</span><span class="n">category</span><span class="p">,</span> <span class="ne">DeprecationWarning</span><span class="p">)</span>566    <span class="k">assert</span> <span class="s2">&quot;deprecated&quot;</span> <span class="ow">in</span> <span class="nb">str</span><span class="p">(</span><span class="n">w</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span><span class="o">.</span><span class="n">message</span><span class="p">)</span>567</pre></div>568</div>569<p>One can also cause all warnings to be exceptions by using <code class="docutils literal notranslate"><span class="pre">error</span></code> instead of570<code class="docutils literal notranslate"><span class="pre">always</span></code>. One thing to be aware of is that if a warning has already been571raised because of a <code class="docutils literal notranslate"><span class="pre">once</span></code>/<code class="docutils literal notranslate"><span class="pre">default</span></code> rule, then no matter what filters are572set the warning will not be seen again unless the warnings registry related to573the warning has been cleared.</p>574<p>Once the context manager exits, the warnings filter is restored to its state575when the context was entered. This prevents tests from changing the warnings576filter in unexpected ways between tests and leading to indeterminate test577results.</p>578<blockquote>579<div><div class="admonition note">580<p class="admonition-title">Note</p>581<p>See <a class="reference internal" href="#warning-concurrent-safe"><span class="std std-ref">Concurrent safety of Context Managers</span></a> for details on the582concurrency-safety of the <a class="reference internal" href="#warnings.catch_warnings" title="warnings.catch_warnings"><code class="xref py py-class docutils literal notranslate"><span class="pre">catch_warnings</span></code></a> context manager when583used in programs using multiple threads or async functions.</p>584</div>585</div></blockquote>586<p>When testing multiple operations that raise the same kind of warning, it587is important to test them in a manner that confirms each operation is raising588a new warning (e.g. set warnings to be raised as exceptions and check the589operations raise exceptions, check that the length of the warning list590continues to increase after each operation, or else delete the previous591entries from the warnings list before each new operation).</p>592</section>593<section id="updating-code-for-new-versions-of-dependencies">594<span id="warning-ignored"></span><h2>Updating Code For New Versions of Dependencies<a class="headerlink" href="#updating-code-for-new-versions-of-dependencies" title="Link to this heading">¶</a></h2>595<p>Warning categories that are primarily of interest to Python developers (rather596than end users of applications written in Python) are ignored by default.</p>597<p>Notably, this “ignored by default” list includes <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>598(for every module except <code class="docutils literal notranslate"><span class="pre">__main__</span></code>), which means developers should make sure599to test their code with typically ignored warnings made visible in order to600receive timely notifications of future breaking API changes (whether in the601standard library or third party packages).</p>602<p>In the ideal case, the code will have a suitable test suite, and the test runner603will take care of implicitly enabling all warnings when running tests604(the test runner provided by the <a class="reference internal" href="unittest.html#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a> module does this).</p>605<p>In less ideal cases, applications can be checked for use of deprecated606interfaces by passing <a class="reference internal" href="../using/cmdline.html#cmdoption-W"><code class="xref std std-option docutils literal notranslate"><span class="pre">-Wd</span></code></a> to the Python interpreter (this is607shorthand for <code class="xref std std-option docutils literal notranslate"><span class="pre">-W</span> <span class="pre">default</span></code>) or setting <code class="docutils literal notranslate"><span class="pre">PYTHONWARNINGS=default</span></code> in608the environment. This enables default handling for all warnings, including those609that are ignored by default. To change what action is taken for encountered610warnings you can change what argument is passed to <code class="xref std std-option docutils literal notranslate"><span class="pre">-W</span></code> (e.g.611<code class="xref std std-option docutils literal notranslate"><span class="pre">-W</span> <span class="pre">error</span></code>). See the <code class="xref std std-option docutils literal notranslate"><span class="pre">-W</span></code> flag for more details on what is612possible.</p>613</section>614<section id="available-functions">615<span id="warning-functions"></span><h2>Available Functions<a class="headerlink" href="#available-functions" title="Link to this heading">¶</a></h2>616<dl class="py function">617<dt class="sig sig-object py" id="warnings.warn">618<span class="sig-prename descclassname"><span class="pre">warnings.</span></span><span class="sig-name descname"><span class="pre">warn</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">message</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">category</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">stacklevel</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">1</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">source</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="keyword-only-separator o"><abbr title="Keyword-only parameters separator (PEP 3102)"><span class="pre">*</span></abbr></span></em>, <em class="sig-param"><span class="n"><span class="pre">skip_file_prefixes</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">()</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#warnings.warn" title="Link to this definition">¶</a></dt>619<dd><p>Issue a warning, or maybe ignore it or raise an exception.  The <em>category</em>620argument, if given, must be a <a class="reference internal" href="#warning-categories"><span class="std std-ref">warning category class</span></a>; it621defaults to <a class="reference internal" href="exceptions.html#UserWarning" title="UserWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UserWarning</span></code></a>.  Alternatively, <em>message</em> can be a <a class="reference internal" href="exceptions.html#Warning" title="Warning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Warning</span></code></a> instance,622in which case <em>category</em> will be ignored and <code class="docutils literal notranslate"><span class="pre">message.__class__</span></code> will be used.623In this case, the message text will be <code class="docutils literal notranslate"><span class="pre">str(message)</span></code>. This function raises an624exception if the particular warning issued is changed into an error by the625<a class="reference internal" href="#warning-filter"><span class="std std-ref">warnings filter</span></a>.  The <em>stacklevel</em> argument can be used by wrapper626functions written in Python, like this:</p>627<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span><span class="w"> </span><span class="nf">deprecated_api</span><span class="p">(</span><span class="n">message</span><span class="p">):</span>628    <span class="n">warnings</span><span class="o">.</span><span class="n">warn</span><span class="p">(</span><span class="n">message</span><span class="p">,</span> <span class="ne">DeprecationWarning</span><span class="p">,</span> <span class="n">stacklevel</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span>629</pre></div>630</div>631<p>This makes the warning refer to <code class="docutils literal notranslate"><span class="pre">deprecated_api</span></code>’s caller, rather than to632the source of <code class="docutils literal notranslate"><span class="pre">deprecated_api</span></code> itself (since the latter would defeat the633purpose of the warning message).</p>634<p>The <em>skip_file_prefixes</em> keyword argument can be used to indicate which635stack frames are ignored when counting stack levels. This can be useful when636you want the warning to always appear at call sites outside of a package637when a constant <em>stacklevel</em> does not fit all call paths or is otherwise638challenging to maintain. If supplied, it must be a tuple of strings. When639prefixes are supplied, stacklevel is implicitly overridden to be <code class="docutils literal notranslate"><span class="pre">max(2,</span>640<span class="pre">stacklevel)</span></code>. To cause a warning to be attributed to the caller from641outside of the current package you might write:</p>642<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># example/lower.py</span>643<span class="n">_warn_skips</span> <span class="o">=</span> <span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">dirname</span><span class="p">(</span><span class="vm">__file__</span><span class="p">),)</span>644 645<span class="k">def</span><span class="w"> </span><span class="nf">one_way</span><span class="p">(</span><span class="n">r_luxury_yacht</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">t_wobbler_mangrove</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>646    <span class="k">if</span> <span class="n">r_luxury_yacht</span><span class="p">:</span>647        <span class="n">warnings</span><span class="o">.</span><span class="n">warn</span><span class="p">(</span><span class="s2">&quot;Please migrate to t_wobbler_mangrove=.&quot;</span><span class="p">,</span>648                      <span class="n">skip_file_prefixes</span><span class="o">=</span><span class="n">_warn_skips</span><span class="p">)</span>649 650<span class="c1"># example/higher.py</span>651<span class="kn">from</span><span class="w"> </span><span class="nn">.</span><span class="w"> </span><span class="kn">import</span> <span class="n">lower</span>652 653<span class="k">def</span><span class="w"> </span><span class="nf">another_way</span><span class="p">(</span><span class="o">**</span><span class="n">kw</span><span class="p">):</span>654    <span class="n">lower</span><span class="o">.</span><span class="n">one_way</span><span class="p">(</span><span class="o">**</span><span class="n">kw</span><span class="p">)</span>655</pre></div>656</div>657<p>This makes the warning refer to both the <code class="docutils literal notranslate"><span class="pre">example.lower.one_way()</span></code> and658<code class="docutils literal notranslate"><span class="pre">example.higher.another_way()</span></code> call sites only from calling code living659outside of <code class="docutils literal notranslate"><span class="pre">example</span></code> package.</p>660<p><em>source</em>, if supplied, is the destroyed object which emitted a661<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>662<div class="versionchanged">663<p><span class="versionmodified changed">Changed in version 3.6: </span>Added <em>source</em> parameter.</p>664</div>665<div class="versionchanged">666<p><span class="versionmodified changed">Changed in version 3.12: </span>Added <em>skip_file_prefixes</em>.</p>667</div>668</dd></dl>669 670<dl class="py function">671<dt class="sig sig-object py" id="warnings.warn_explicit">672<span class="sig-prename descclassname"><span class="pre">warnings.</span></span><span class="sig-name descname"><span class="pre">warn_explicit</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">message</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">category</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">filename</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">lineno</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">module</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">registry</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">module_globals</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">source</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="#warnings.warn_explicit" title="Link to this definition">¶</a></dt>673<dd><p>This is a low-level interface to the functionality of <a class="reference internal" href="#warnings.warn" title="warnings.warn"><code class="xref py py-func docutils literal notranslate"><span class="pre">warn()</span></code></a>, passing in674explicitly the message, category, filename and line number, and optionally675other arguments.676<em>message</em> must be a string and <em>category</em> a subclass of <a class="reference internal" href="exceptions.html#Warning" title="Warning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Warning</span></code></a> or677<em>message</em> may be a <code class="xref py py-exc docutils literal notranslate"><span class="pre">Warning</span></code> instance, in which case <em>category</em> will be678ignored.</p>679<p><em>module</em>, if supplied, should be the module name.680If no module is passed, the module regular expression in681<a class="reference internal" href="#warning-filter"><span class="std std-ref">warnings filter</span></a> will be tested against the module682names constructed from the path components starting from all parent683directories (with <code class="docutils literal notranslate"><span class="pre">/__init__.py</span></code>, <code class="docutils literal notranslate"><span class="pre">.py</span></code> and, on Windows, <code class="docutils literal notranslate"><span class="pre">.pyw</span></code>684stripped) and against the filename with <code class="docutils literal notranslate"><span class="pre">.py</span></code> stripped.685For example, when the filename is <code class="docutils literal notranslate"><span class="pre">'/path/to/package/module.py'</span></code>, it will686be tested against  <code class="docutils literal notranslate"><span class="pre">'path.to.package.module'</span></code>, <code class="docutils literal notranslate"><span class="pre">'to.package.module'</span></code>687<code class="docutils literal notranslate"><span class="pre">'package.module'</span></code>, <code class="docutils literal notranslate"><span class="pre">'module'</span></code>, and <code class="docutils literal notranslate"><span class="pre">'/path/to/package/module'</span></code>.</p>688<p><em>registry</em>, if supplied, should be the <code class="docutils literal notranslate"><span class="pre">__warningregistry__</span></code> dictionary689of the module.690If no registry is passed, each warning is treated as the first occurrence,691that is, filter actions <code class="docutils literal notranslate"><span class="pre">&quot;default&quot;</span></code>, <code class="docutils literal notranslate"><span class="pre">&quot;module&quot;</span></code> and <code class="docutils literal notranslate"><span class="pre">&quot;once&quot;</span></code> are692handled as <code class="docutils literal notranslate"><span class="pre">&quot;always&quot;</span></code>.</p>693<p><em>module_globals</em>, if supplied, should be the global namespace in use by the code694for which the warning is issued.  (This argument is used to support displaying695source for modules found in zipfiles or other non-filesystem import696sources).</p>697<p><em>source</em>, if supplied, is the destroyed object which emitted a698<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>699<div class="versionchanged">700<p><span class="versionmodified changed">Changed in version 3.6: </span>Add the <em>source</em> parameter.</p>701</div>702<div class="versionchanged">703<p><span class="versionmodified changed">Changed in version 3.15: </span>If no module is passed, test the filter regular expression against704module names created from the path, not only the path itself.</p>705</div>706</dd></dl>707 708<dl class="py function">709<dt class="sig sig-object py" id="warnings.showwarning">710<span class="sig-prename descclassname"><span class="pre">warnings.</span></span><span class="sig-name descname"><span class="pre">showwarning</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">message</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">category</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">filename</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">lineno</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">file</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">line</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="#warnings.showwarning" title="Link to this definition">¶</a></dt>711<dd><p>Write a warning to a file.  The default implementation calls712<code class="docutils literal notranslate"><span class="pre">formatwarning(message,</span> <span class="pre">category,</span> <span class="pre">filename,</span> <span class="pre">lineno,</span> <span class="pre">line)</span></code> and writes the713resulting string to <em>file</em>, which defaults to <a class="reference internal" href="sys.html#sys.stderr" title="sys.stderr"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.stderr</span></code></a>.  You may replace714this function with any callable by assigning to <code class="docutils literal notranslate"><span class="pre">warnings.showwarning</span></code>.715<em>line</em> is a line of source code to be included in the warning716message; if <em>line</em> is not supplied, <code class="xref py py-func docutils literal notranslate"><span class="pre">showwarning()</span></code> will717try to read the line specified by <em>filename</em> and <em>lineno</em>.</p>718</dd></dl>719 720<dl class="py function">721<dt class="sig sig-object py" id="warnings.formatwarning">722<span class="sig-prename descclassname"><span class="pre">warnings.</span></span><span class="sig-name descname"><span class="pre">formatwarning</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">message</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">category</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">filename</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">lineno</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">line</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="#warnings.formatwarning" title="Link to this definition">¶</a></dt>723<dd><p>Format a warning the standard way.  This returns a string which may contain724embedded newlines and ends in a newline.  <em>line</em> is a line of source code to725be included in the warning message; if <em>line</em> is not supplied,726<code class="xref py py-func docutils literal notranslate"><span class="pre">formatwarning()</span></code> will try to read the line specified by <em>filename</em> and727<em>lineno</em>.</p>728</dd></dl>729 730<dl class="py function">731<dt class="sig sig-object py" id="warnings.filterwarnings">732<span class="sig-prename descclassname"><span class="pre">warnings.</span></span><span class="sig-name descname"><span class="pre">filterwarnings</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">action</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">message</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">''</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">category</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">Warning</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">module</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">''</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">lineno</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">0</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">append</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">False</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#warnings.filterwarnings" title="Link to this definition">¶</a></dt>733<dd><p>Insert an entry into the list of <a class="reference internal" href="#warning-filter"><span class="std std-ref">warnings filter specifications</span></a>.  The entry is inserted at the front by default; if734<em>append</em> is true, it is inserted at the end.  This checks the types of the735arguments, compiles the <em>message</em> and <em>module</em> regular expressions, and736inserts them as a tuple in the list of warnings filters.  Entries closer to737the front of the list override entries later in the list, if both match a738particular warning.  Omitted arguments default to a value that matches739everything.</p>740</dd></dl>741 742<dl class="py function">743<dt class="sig sig-object py" id="warnings.simplefilter">744<span class="sig-prename descclassname"><span class="pre">warnings.</span></span><span class="sig-name descname"><span class="pre">simplefilter</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">action</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">category</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">Warning</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">lineno</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">0</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">append</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">False</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#warnings.simplefilter" title="Link to this definition">¶</a></dt>745<dd><p>Insert a simple entry into the list of <a class="reference internal" href="#warning-filter"><span class="std std-ref">warnings filter specifications</span></a>.  The meaning of the function parameters is as for746<a class="reference internal" href="#warnings.filterwarnings" title="warnings.filterwarnings"><code class="xref py py-func docutils literal notranslate"><span class="pre">filterwarnings()</span></code></a>, but regular expressions are not needed as the filter747inserted always matches any message in any module as long as the category and748line number match.</p>749</dd></dl>750 751<dl class="py function">752<dt class="sig sig-object py" id="warnings.resetwarnings">753<span class="sig-prename descclassname"><span class="pre">warnings.</span></span><span class="sig-name descname"><span class="pre">resetwarnings</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#warnings.resetwarnings" title="Link to this definition">¶</a></dt>754<dd><p>Reset the warnings filter.  This discards the effect of all previous calls to755<a class="reference internal" href="#warnings.filterwarnings" title="warnings.filterwarnings"><code class="xref py py-func docutils literal notranslate"><span class="pre">filterwarnings()</span></code></a>, including that of the <a class="reference internal" href="../using/cmdline.html#cmdoption-W"><code class="xref std std-option docutils literal notranslate"><span class="pre">-W</span></code></a> command line options756and calls to <a class="reference internal" href="#warnings.simplefilter" title="warnings.simplefilter"><code class="xref py py-func docutils literal notranslate"><span class="pre">simplefilter()</span></code></a>.</p>757</dd></dl>758 759<dl class="py function">760<dt class="sig sig-object py" id="warnings.deprecated">761<span class="sig-prename descclassname"><span class="pre">&#64;</span></span><span class="sig-prename descclassname"><span class="pre">warnings.</span></span><span class="sig-name descname"><span class="pre">deprecated</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">msg</span></span></em>, <em class="sig-param"><span class="keyword-only-separator o"><abbr title="Keyword-only parameters separator (PEP 3102)"><span class="pre">*</span></abbr></span></em>, <em class="sig-param"><span class="n"><span class="pre">category</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">DeprecationWarning</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">stacklevel</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">1</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#warnings.deprecated" title="Link to this definition">¶</a></dt>762<dd><p>Decorator to indicate that a class, function or overload is deprecated.</p>763<p>When this decorator is applied to an object,764deprecation warnings may be emitted at runtime when the object is used.765<a class="reference internal" href="../glossary.html#term-static-type-checker"><span class="xref std std-term">static type checkers</span></a>766will also generate a diagnostic on usage of the deprecated object.</p>767<p>Usage:</p>768<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span><span class="w"> </span><span class="nn">warnings</span><span class="w"> </span><span class="kn">import</span> <span class="n">deprecated</span>769<span class="kn">from</span><span class="w"> </span><span class="nn">typing</span><span class="w"> </span><span class="kn">import</span> <span class="n">overload</span>770 771<span class="nd">@deprecated</span><span class="p">(</span><span class="s2">&quot;Use B instead&quot;</span><span class="p">)</span>772<span class="k">class</span><span class="w"> </span><span class="nc">A</span><span class="p">:</span>773    <span class="k">pass</span>774 775<span class="nd">@deprecated</span><span class="p">(</span><span class="s2">&quot;Use g instead&quot;</span><span class="p">)</span>776<span class="k">def</span><span class="w"> </span><span class="nf">f</span><span class="p">():</span>777    <span class="k">pass</span>778 779<span class="nd">@overload</span>780<span class="nd">@deprecated</span><span class="p">(</span><span class="s2">&quot;int support is deprecated&quot;</span><span class="p">)</span>781<span class="k">def</span><span class="w"> </span><span class="nf">g</span><span class="p">(</span><span class="n">x</span><span class="p">:</span> <span class="nb">int</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="nb">int</span><span class="p">:</span> <span class="o">...</span>782<span class="nd">@overload</span>783<span class="k">def</span><span class="w"> </span><span class="nf">g</span><span class="p">(</span><span class="n">x</span><span class="p">:</span> <span class="nb">str</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="nb">int</span><span class="p">:</span> <span class="o">...</span>784</pre></div>785</div>786<p>The warning specified by <em>category</em> will be emitted at runtime787on use of deprecated objects. For functions, that happens on calls;788for classes, on instantiation and on creation of subclasses.789If the <em>category</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>, no warning is emitted at runtime.790The <em>stacklevel</em> determines where the791warning is emitted. If it is <code class="docutils literal notranslate"><span class="pre">1</span></code> (the default), the warning792is emitted at the direct caller of the deprecated object; if it793is higher, it is emitted further up the stack.794Static type checker behavior is not affected by the <em>category</em>795and <em>stacklevel</em> arguments.</p>796<p>The deprecation message passed to the decorator is saved in the797<code class="docutils literal notranslate"><span class="pre">__deprecated__</span></code> attribute on the decorated object.798If applied to an overload, the decorator799must be after the <a class="reference internal" href="typing.html#typing.overload" title="typing.overload"><code class="xref py py-deco docutils literal notranslate"><span class="pre">&#64;~typing.overload</span></code></a> decorator800for the attribute to exist on the overload as returned by801<a class="reference internal" href="typing.html#typing.get_overloads" title="typing.get_overloads"><code class="xref py py-func docutils literal notranslate"><span class="pre">typing.get_overloads()</span></code></a>.</p>802<div class="versionadded">803<p><span class="versionmodified added">Added in version 3.13: </span>See <span class="target" id="index-6"></span><a class="pep reference external" href="https://peps.python.org/pep-0702/"><strong>PEP 702</strong></a>.</p>804</div>805</dd></dl>806 807</section>808<section id="available-context-managers">809<h2>Available Context Managers<a class="headerlink" href="#available-context-managers" title="Link to this heading">¶</a></h2>810<dl class="py class">811<dt class="sig sig-object py" id="warnings.catch_warnings">812<em class="property"><span class="k"><span class="pre">class</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">warnings.</span></span><span class="sig-name descname"><span class="pre">catch_warnings</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="keyword-only-separator o"><abbr title="Keyword-only parameters separator (PEP 3102)"><span class="pre">*</span></abbr></span></em>, <em class="sig-param"><span class="n"><span class="pre">record</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">False</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">module</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">action</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">category</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">Warning</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">lineno</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">0</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">append</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">False</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#warnings.catch_warnings" title="Link to this definition">¶</a></dt>813<dd><p>A context manager that copies and, upon exit, restores the warnings filter814and the <a class="reference internal" href="#warnings.showwarning" title="warnings.showwarning"><code class="xref py py-func docutils literal notranslate"><span class="pre">showwarning()</span></code></a> function.815If the <em>record</em> argument is <a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a> (the default) the context manager816returns <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-class docutils literal notranslate"><span class="pre">None</span></code></a> on entry. If <em>record</em> is <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a>, a list is817returned that is progressively populated with objects as seen by a custom818<code class="xref py py-func docutils literal notranslate"><span class="pre">showwarning()</span></code> function (which also suppresses output to <code class="docutils literal notranslate"><span class="pre">sys.stdout</span></code>).819Each object in the list has attributes with the same names as the arguments to820<code class="xref py py-func docutils literal notranslate"><span class="pre">showwarning()</span></code>.</p>821<p>The <em>module</em> argument takes a module that will be used instead of the822module returned when you import <code class="xref py py-mod docutils literal notranslate"><span class="pre">warnings</span></code> whose filter will be823protected. This argument exists primarily for testing the <code class="xref py py-mod docutils literal notranslate"><span class="pre">warnings</span></code>824module itself.</p>825<p>If the <em>action</em> argument is not <code class="docutils literal notranslate"><span class="pre">None</span></code>, the remaining arguments are826passed to <a class="reference internal" href="#warnings.simplefilter" title="warnings.simplefilter"><code class="xref py py-func docutils literal notranslate"><span class="pre">simplefilter()</span></code></a> as if it were called immediately on827entering the context.</p>828<p>See <a class="reference internal" href="#warning-filter"><span class="std std-ref">The Warnings Filter</span></a> for the meaning of the <em>category</em> and <em>lineno</em>829parameters.</p>830<div class="admonition note">831<p class="admonition-title">Note</p>832<p>See <a class="reference internal" href="#warning-concurrent-safe"><span class="std std-ref">Concurrent safety of Context Managers</span></a> for details on the833concurrency-safety of the <code class="xref py py-class docutils literal notranslate"><span class="pre">catch_warnings</span></code> context manager when834used in programs using multiple threads or async functions.</p>835</div>836<div class="versionchanged">837<p><span class="versionmodified changed">Changed in version 3.11: </span>Added the <em>action</em>, <em>category</em>, <em>lineno</em>, and <em>append</em> parameters.</p>838</div>839</dd></dl>840 841</section>842<section id="concurrent-safety-of-context-managers">843<span id="warning-concurrent-safe"></span><h2>Concurrent safety of Context Managers<a class="headerlink" href="#concurrent-safety-of-context-managers" title="Link to this heading">¶</a></h2>844<p>The behavior of <a class="reference internal" href="#warnings.catch_warnings" title="warnings.catch_warnings"><code class="xref py py-class docutils literal notranslate"><span class="pre">catch_warnings</span></code></a> context manager depends on the845<a class="reference internal" href="sys.html#sys.flags.context_aware_warnings" title="sys.flags.context_aware_warnings"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.flags.context_aware_warnings</span></code></a> flag.  If the flag is true, the846context manager behaves in a concurrent-safe fashion and otherwise not.847Concurrent-safe means that it is both thread-safe and safe to use within848<a class="reference internal" href="asyncio-task.html#coroutine"><span class="std std-ref">asyncio coroutines</span></a> and tasks.  Being thread-safe means849that behavior is predictable in a multi-threaded program.  The flag defaults850to true for free-threaded builds and false otherwise.</p>851<p>If the <a class="reference internal" href="sys.html#sys.flags.context_aware_warnings" title="sys.flags.context_aware_warnings"><code class="xref py py-data docutils literal notranslate"><span class="pre">context_aware_warnings</span></code></a> flag is false, then852<a class="reference internal" href="#warnings.catch_warnings" title="warnings.catch_warnings"><code class="xref py py-class docutils literal notranslate"><span class="pre">catch_warnings</span></code></a> will modify the global attributes of the853<code class="xref py py-mod docutils literal notranslate"><span class="pre">warnings</span></code> module.  This is not safe if used within a concurrent program854(using multiple threads or using asyncio coroutines).  For example, if two855or more threads use the <code class="xref py py-class docutils literal notranslate"><span class="pre">catch_warnings</span></code> class at the same time, the856behavior is undefined.</p>857<p>If the flag is true, <a class="reference internal" href="#warnings.catch_warnings" title="warnings.catch_warnings"><code class="xref py py-class docutils literal notranslate"><span class="pre">catch_warnings</span></code></a> will not modify global858attributes and will instead use a <a class="reference internal" href="contextvars.html#contextvars.ContextVar" title="contextvars.ContextVar"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContextVar</span></code></a> to859store the newly established warning filtering state.  A context variable860provides thread-local storage and it makes the use of <code class="xref py py-class docutils literal notranslate"><span class="pre">catch_warnings</span></code>861thread-safe.</p>862<p>The <em>record</em> parameter of the context handler also behaves differently863depending on the value of the flag.  When <em>record</em> is true and the flag is864false, the context manager works by replacing and then later restoring the865module’s <a class="reference internal" href="#warnings.showwarning" title="warnings.showwarning"><code class="xref py py-func docutils literal notranslate"><span class="pre">showwarning()</span></code></a> function.  That is not concurrent-safe.</p>866<p>When <em>record</em> is true and the flag is true, the <a class="reference internal" href="#warnings.showwarning" title="warnings.showwarning"><code class="xref py py-func docutils literal notranslate"><span class="pre">showwarning()</span></code></a> function867is not replaced.  Instead, the recording status is indicated by an internal868property in the context variable.  In this case, the <code class="xref py py-func docutils literal notranslate"><span class="pre">showwarning()</span></code>869function will not be restored when exiting the context handler.</p>870<p>The <a class="reference internal" href="sys.html#sys.flags.context_aware_warnings" title="sys.flags.context_aware_warnings"><code class="xref py py-data docutils literal notranslate"><span class="pre">context_aware_warnings</span></code></a> flag can be set 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>871<span class="pre">context_aware_warnings</span></code></a> command-line option or by the872<span class="target" id="index-7"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHON_CONTEXT_AWARE_WARNINGS"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHON_CONTEXT_AWARE_WARNINGS</span></code></a> environment variable.</p>873<blockquote>874<div><div class="admonition note">875<p class="admonition-title">Note</p>876<p>It is likely that most programs that desire thread-safe877behaviour of the warnings module will also want to set the878<a class="reference internal" href="sys.html#sys.flags.thread_inherit_context" title="sys.flags.thread_inherit_context"><code class="xref py py-data docutils literal notranslate"><span class="pre">thread_inherit_context</span></code></a> flag to true.  That flag879causes threads created by <a class="reference internal" href="threading.html#threading.Thread" title="threading.Thread"><code class="xref py py-class docutils literal notranslate"><span class="pre">threading.Thread</span></code></a> to start880with a copy of the context variables from the thread starting881it.  When true, the context established by <a class="reference internal" href="#warnings.catch_warnings" title="warnings.catch_warnings"><code class="xref py py-class docutils literal notranslate"><span class="pre">catch_warnings</span></code></a>882in one thread will also apply to new threads started by it.  If false,883new threads will start with an empty warnings context variable,884meaning that any filtering that was established by a885<code class="xref py py-class docutils literal notranslate"><span class="pre">catch_warnings</span></code> context manager will no longer be active.</p>886</div>887</div></blockquote>888<div class="versionchanged">889<p><span class="versionmodified changed">Changed in version 3.14: </span>Added the <a class="reference internal" href="sys.html#sys.flags.context_aware_warnings" title="sys.flags.context_aware_warnings"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.flags.context_aware_warnings</span></code></a> flag and the use of a890context variable for <a class="reference internal" href="#warnings.catch_warnings" title="warnings.catch_warnings"><code class="xref py py-class docutils literal notranslate"><span class="pre">catch_warnings</span></code></a> if the flag is true.  Previous891versions of Python acted as if the flag was always set to false.</p>892</div>893</section>894</section>895 896 897            <div class="clearer"></div>898          </div>899        </div>900      </div>901      <div class="sphinxsidebar" role="navigation" aria-label="Main">902        <div class="sphinxsidebarwrapper">903  <div>904    <h3><a href="../contents.html">Table of Contents</a></h3>905    <ul>906<li><a class="reference internal" href="#"><code class="xref py py-mod docutils literal notranslate"><span class="pre">warnings</span></code> — Warning control</a><ul>907<li><a class="reference internal" href="#warning-categories">Warning Categories</a></li>908<li><a class="reference internal" href="#the-warnings-filter">The Warnings Filter</a><ul>909<li><a class="reference internal" href="#repeated-warning-suppression-criteria">Repeated Warning Suppression Criteria</a></li>910<li><a class="reference internal" href="#describing-warning-filters">Describing Warning Filters</a></li>911<li><a class="reference internal" href="#default-warning-filter">Default Warning Filter</a></li>912<li><a class="reference internal" href="#overriding-the-default-filter">Overriding the default filter</a></li>913</ul>914</li>915<li><a class="reference internal" href="#temporarily-suppressing-warnings">Temporarily Suppressing Warnings</a></li>916<li><a class="reference internal" href="#testing-warnings">Testing Warnings</a></li>917<li><a class="reference internal" href="#updating-code-for-new-versions-of-dependencies">Updating Code For New Versions of Dependencies</a></li>918<li><a class="reference internal" href="#available-functions">Available Functions</a></li>919<li><a class="reference internal" href="#available-context-managers">Available Context Managers</a></li>920<li><a class="reference internal" href="#concurrent-safety-of-context-managers">Concurrent safety of Context Managers</a></li>921</ul>922</li>923</ul>924 925  </div>926  <div>927    <h4>Previous topic</h4>928    <p class="topless"><a href="__main__.html"929                          title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">__main__</span></code> — Top-level code environment</a></p>930  </div>931  <div>932    <h4>Next topic</h4>933    <p class="topless"><a href="dataclasses.html"934                          title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">dataclasses</span></code> — Data Classes</a></p>935  </div>936  <script>937    document.addEventListener('DOMContentLoaded', () => {938        const title = document.querySelector('meta[property="og:title"]').content;939        const elements = document.querySelectorAll('.improvepage');940        const pageurl = window.location.href.split('?')[0];941        elements.forEach(element => {942            const url = new URL(element.href.split('?')[0].replace("-nojs", ""));943            url.searchParams.set('pagetitle', title);944            url.searchParams.set('pageurl', pageurl);945            url.searchParams.set('pagesource', "library/warnings.rst");946            element.href = url.toString();947        });948    });949  </script>950  <div role="note" aria-label="source link">951    <h3>This page</h3>952    <ul class="this-page-menu">953      <li><a href="../bugs.html">Report a bug</a></li>954      <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li>955      <li>956        <a href="https://github.com/python/cpython/blob/main/Doc/library/warnings.rst?plain=1"957            rel="nofollow">Show source958        </a>959      </li>960      961    </ul>962  </div>963        </div>964<div id="sidebarbutton" title="Collapse sidebar">965<span>«</span>966</div>967 968      </div>969      <div class="clearer"></div>970    </div>  971    <div class="related" role="navigation" aria-label="Related">972      <h3>Navigation</h3>973      <ul>974        <li class="right" style="margin-right: 10px">975          <a href="../genindex.html" title="General Index"976             >index</a></li>977        <li class="right" >978          <a href="../py-modindex.html" title="Python Module Index"979             >modules</a> |</li>980        <li class="right" >981          <a href="dataclasses.html" title="dataclasses — Data Classes"982             >next</a> |</li>983        <li class="right" >984          <a href="__main__.html" title="__main__ — Top-level code environment"985             >previous</a> |</li>986 987          <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li>988          <li><a href="https://www.python.org/">Python</a> &#187;</li>989          <li class="switchers">990            <div class="language_switcher_placeholder"></div>991            <div class="version_switcher_placeholder"></div>992          </li>993          <li>994              995          </li>996    <li id="cpython-language-and-version">997      <a href="../index.html">3.15.0a6 Documentation</a> &#187;998    </li>999 1000          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>1001          <li class="nav-item nav-item-2"><a href="python.html" >Python Runtime Services</a> &#187;</li>1002        <li class="nav-item nav-item-this"><a href=""><code class="xref py py-mod docutils literal notranslate"><span class="pre">warnings</span></code> — Warning control</a></li>1003                <li class="right">1004                    1005 1006    <div class="inline-search" role="search">1007        <form class="inline-search" action="../search.html" method="get">1008          <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box">1009          <input type="submit" value="Go">1010        </form>1011    </div>1012                     |1013                </li>1014            <li class="right">1015<label class="theme-selector-label">1016    Theme1017    <select class="theme-selector" oninput="activateTheme(this.value)">1018        <option value="auto" selected>Auto</option>1019        <option value="light">Light</option>1020        <option value="dark">Dark</option>1021    </select>1022</label> |</li>1023            1024      </ul>1025    </div>  1026    <div class="footer">1027    &copy; <a href="../copyright.html">Copyright</a> 2001 Python Software Foundation.1028    <br>1029    This page is licensed under the Python Software Foundation License Version 2.1030    <br>1031    Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.1032    <br>1033    1034      See <a href="/license.html">History and License</a> for more information.<br>1035    1036    1037    <br>1038 1039    The Python Software Foundation is a non-profit corporation.1040<a href="https://www.python.org/psf/donations/">Please donate.</a>1041<br>1042    <br>1043      Last updated on Mar 10, 2026 (08:58 UTC).1044    1045      <a href="/bugs.html">Found a bug</a>?1046    1047    <br>1048 1049    Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3.1050    </div>1051 1052  </body>1053</html>