Team Ai
Apppublic

parthtamu/rag-code-assistant

sourceHugging Faceupdated 7mo agoView on Hugging Face
0likes
contextvars.html724 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="contextvars — Context Variables" />8<meta property="og:type" content="website" />9<meta property="og:url" content="https://docs.python.org/3/library/contextvars.html" />10<meta property="og:site_name" content="Python documentation" />11<meta property="og:description" content="This module provides APIs to manage, store, and access context-local state. The ContextVar class is used to declare and work with Context Variables. The copy_context() function and the Context clas..." />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_contextvars_0dbe76df.png" />15<meta property="og:image:alt" content="This module provides APIs to manage, store, and access context-local state. The ContextVar class is used to declare and work with Context Variables. The copy_context() function and the Context clas..." />16<meta name="description" content="This module provides APIs to manage, store, and access context-local state. The ContextVar class is used to declare and work with Context Variables. The copy_context() function and the Context clas..." />17<meta name="twitter:card" content="summary_large_image" />18<meta name="theme-color" content="#3776ab">19 20    <title>contextvars — Context Variables &#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="_thread — Low-level threading API" href="_thread.html" />43    <link rel="prev" title="queue — A synchronized queue class" href="queue.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/contextvars.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">contextvars</span></code> — Context Variables</a><ul>108<li><a class="reference internal" href="#context-variables">Context Variables</a></li>109<li><a class="reference internal" href="#manual-context-management">Manual Context Management</a></li>110<li><a class="reference internal" href="#asyncio-support">asyncio support</a></li>111</ul>112</li>113</ul>114 115  </div>116  <div>117    <h4>Previous topic</h4>118    <p class="topless"><a href="queue.html"119                          title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">queue</span></code> — A synchronized queue class</a></p>120  </div>121  <div>122    <h4>Next topic</h4>123    <p class="topless"><a href="_thread.html"124                          title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">_thread</span></code> — Low-level threading API</a></p>125  </div>126  <script>127    document.addEventListener('DOMContentLoaded', () => {128        const title = document.querySelector('meta[property="og:title"]').content;129        const elements = document.querySelectorAll('.improvepage');130        const pageurl = window.location.href.split('?')[0];131        elements.forEach(element => {132            const url = new URL(element.href.split('?')[0].replace("-nojs", ""));133            url.searchParams.set('pagetitle', title);134            url.searchParams.set('pageurl', pageurl);135            url.searchParams.set('pagesource', "library/contextvars.rst");136            element.href = url.toString();137        });138    });139  </script>140  <div role="note" aria-label="source link">141    <h3>This page</h3>142    <ul class="this-page-menu">143      <li><a href="../bugs.html">Report a bug</a></li>144      <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li>145      <li>146        <a href="https://github.com/python/cpython/blob/main/Doc/library/contextvars.rst?plain=1"147            rel="nofollow">Show source148        </a>149      </li>150      151    </ul>152  </div>153        </nav>154    </div>155</div>156 157  158    <div class="related" role="navigation" aria-label="Related">159      <h3>Navigation</h3>160      <ul>161        <li class="right" style="margin-right: 10px">162          <a href="../genindex.html" title="General Index"163             accesskey="I">index</a></li>164        <li class="right" >165          <a href="../py-modindex.html" title="Python Module Index"166             >modules</a> |</li>167        <li class="right" >168          <a href="_thread.html" title="_thread — Low-level threading API"169             accesskey="N">next</a> |</li>170        <li class="right" >171          <a href="queue.html" title="queue — A synchronized queue class"172             accesskey="P">previous</a> |</li>173 174          <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li>175          <li><a href="https://www.python.org/">Python</a> &#187;</li>176          <li class="switchers">177            <div class="language_switcher_placeholder"></div>178            <div class="version_switcher_placeholder"></div>179          </li>180          <li>181              182          </li>183    <li id="cpython-language-and-version">184      <a href="../index.html">3.15.0a6 Documentation</a> &#187;185    </li>186 187          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>188          <li class="nav-item nav-item-2"><a href="concurrency.html" accesskey="U">Concurrent Execution</a> &#187;</li>189        <li class="nav-item nav-item-this"><a href=""><code class="xref py py-mod docutils literal notranslate"><span class="pre">contextvars</span></code> — Context Variables</a></li>190                <li class="right">191                    192 193    <div class="inline-search" role="search">194        <form class="inline-search" action="../search.html" method="get">195          <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box">196          <input type="submit" value="Go">197        </form>198    </div>199                     |200                </li>201            <li class="right">202<label class="theme-selector-label">203    Theme204    <select class="theme-selector" oninput="activateTheme(this.value)">205        <option value="auto" selected>Auto</option>206        <option value="light">Light</option>207        <option value="dark">Dark</option>208    </select>209</label> |</li>210            211      </ul>212    </div>    213 214    <div class="document">215      <div class="documentwrapper">216        <div class="bodywrapper">217          <div class="body" role="main">218            219  <section id="module-contextvars">220<span id="contextvars-context-variables"></span><h1><code class="xref py py-mod docutils literal notranslate"><span class="pre">contextvars</span></code> — Context Variables<a class="headerlink" href="#module-contextvars" title="Link to this heading">¶</a></h1>221<hr class="docutils" />222<p>This module provides APIs to manage, store, and access context-local223state.  The <a class="reference internal" href="#contextvars.ContextVar" title="contextvars.ContextVar"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContextVar</span></code></a> class is used to declare224and work with <em>Context Variables</em>.  The <a class="reference internal" href="#contextvars.copy_context" title="contextvars.copy_context"><code class="xref py py-func docutils literal notranslate"><span class="pre">copy_context()</span></code></a>225function and the <a class="reference internal" href="#contextvars.Context" title="contextvars.Context"><code class="xref py py-class docutils literal notranslate"><span class="pre">Context</span></code></a> class should be used to226manage the current context in asynchronous frameworks.</p>227<p>Context managers that have state should use Context Variables228instead of <a class="reference internal" href="threading.html#threading.local" title="threading.local"><code class="xref py py-func docutils literal notranslate"><span class="pre">threading.local()</span></code></a> to prevent their state from229bleeding to other code unexpectedly, when used in concurrent code.</p>230<p>See also <span class="target" id="index-0"></span><a class="pep reference external" href="https://peps.python.org/pep-0567/"><strong>PEP 567</strong></a> for additional details.</p>231<div class="versionadded">232<p><span class="versionmodified added">Added in version 3.7.</span></p>233</div>234<section id="context-variables">235<h2>Context Variables<a class="headerlink" href="#context-variables" title="Link to this heading">¶</a></h2>236<dl class="py class">237<dt class="sig sig-object py" id="contextvars.ContextVar">238<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">contextvars.</span></span><span class="sig-name descname"><span class="pre">ContextVar</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">name</span></span></em><span class="optional">[</span>, <em class="sig-param"><span class="n"><span class="pre">*</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">default</span></span></em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#contextvars.ContextVar" title="Link to this definition">¶</a></dt>239<dd><p>This class is used to declare a new Context Variable, e.g.:</p>240<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">var</span><span class="p">:</span> <span class="n">ContextVar</span><span class="p">[</span><span class="nb">int</span><span class="p">]</span> <span class="o">=</span> <span class="n">ContextVar</span><span class="p">(</span><span class="s1">&#39;var&#39;</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="mi">42</span><span class="p">)</span>241</pre></div>242</div>243<p>The required <em>name</em> parameter is used for introspection and debug244purposes.</p>245<p>The optional keyword-only <em>default</em> parameter is returned by246<a class="reference internal" href="#contextvars.ContextVar.get" title="contextvars.ContextVar.get"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ContextVar.get()</span></code></a> when no value for the variable is found247in the current context.</p>248<p><strong>Important:</strong> Context Variables should be created at the top module249level and never in closures.  <a class="reference internal" href="#contextvars.Context" title="contextvars.Context"><code class="xref py py-class docutils literal notranslate"><span class="pre">Context</span></code></a> objects hold strong250references to context variables which prevents context variables251from being properly garbage collected.</p>252<dl class="py attribute">253<dt class="sig sig-object py" id="contextvars.ContextVar.name">254<span class="sig-name descname"><span class="pre">name</span></span><a class="headerlink" href="#contextvars.ContextVar.name" title="Link to this definition">¶</a></dt>255<dd><p>The name of the variable.  This is a read-only property.</p>256<div class="versionadded">257<p><span class="versionmodified added">Added in version 3.7.1.</span></p>258</div>259</dd></dl>260 261<dl class="py method">262<dt class="sig sig-object py" id="contextvars.ContextVar.get">263<span class="sig-name descname"><span class="pre">get</span></span><span class="sig-paren">(</span><span class="optional">[</span><em class="sig-param"><span class="n"><span class="pre">default</span></span></em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#contextvars.ContextVar.get" title="Link to this definition">¶</a></dt>264<dd><p>Return a value for the context variable for the current context.</p>265<p>If there is no value for the variable in the current context,266the method will:</p>267<ul class="simple">268<li><p>return the value of the <em>default</em> argument of the method,269if provided; or</p></li>270<li><p>return the default value for the context variable,271if it was created with one; or</p></li>272<li><p>raise a <a class="reference internal" href="exceptions.html#LookupError" title="LookupError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">LookupError</span></code></a>.</p></li>273</ul>274</dd></dl>275 276<dl class="py method">277<dt class="sig sig-object py" id="contextvars.ContextVar.set">278<span class="sig-name descname"><span class="pre">set</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">value</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#contextvars.ContextVar.set" title="Link to this definition">¶</a></dt>279<dd><p>Call to set a new value for the context variable in the current280context.</p>281<p>The required <em>value</em> argument is the new value for the context282variable.</p>283<p>Returns a <a class="reference internal" href="#contextvars.Token" title="contextvars.Token"><code class="xref py py-class docutils literal notranslate"><span class="pre">Token</span></code></a> object that can be used284to restore the variable to its previous value via the285<a class="reference internal" href="#contextvars.ContextVar.reset" title="contextvars.ContextVar.reset"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ContextVar.reset()</span></code></a> method.</p>286<p>For convenience, the token object can be used as a context manager287to avoid calling <a class="reference internal" href="#contextvars.ContextVar.reset" title="contextvars.ContextVar.reset"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ContextVar.reset()</span></code></a> manually:</p>288<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">var</span> <span class="o">=</span> <span class="n">ContextVar</span><span class="p">(</span><span class="s1">&#39;var&#39;</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="s1">&#39;default value&#39;</span><span class="p">)</span>289 290<span class="k">with</span> <span class="n">var</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="s1">&#39;new value&#39;</span><span class="p">):</span>291    <span class="k">assert</span> <span class="n">var</span><span class="o">.</span><span class="n">get</span><span class="p">()</span> <span class="o">==</span> <span class="s1">&#39;new value&#39;</span>292 293<span class="k">assert</span> <span class="n">var</span><span class="o">.</span><span class="n">get</span><span class="p">()</span> <span class="o">==</span> <span class="s1">&#39;default value&#39;</span>294</pre></div>295</div>296<p>It is a shorthand for:</p>297<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">var</span> <span class="o">=</span> <span class="n">ContextVar</span><span class="p">(</span><span class="s1">&#39;var&#39;</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="s1">&#39;default value&#39;</span><span class="p">)</span>298 299<span class="n">token</span> <span class="o">=</span> <span class="n">var</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="s1">&#39;new value&#39;</span><span class="p">)</span>300<span class="k">try</span><span class="p">:</span>301    <span class="k">assert</span> <span class="n">var</span><span class="o">.</span><span class="n">get</span><span class="p">()</span> <span class="o">==</span> <span class="s1">&#39;new value&#39;</span>302<span class="k">finally</span><span class="p">:</span>303    <span class="n">var</span><span class="o">.</span><span class="n">reset</span><span class="p">(</span><span class="n">token</span><span class="p">)</span>304 305<span class="k">assert</span> <span class="n">var</span><span class="o">.</span><span class="n">get</span><span class="p">()</span> <span class="o">==</span> <span class="s1">&#39;default value&#39;</span>306</pre></div>307</div>308<div class="versionadded">309<p><span class="versionmodified added">Added in version 3.14: </span>Added support for using tokens as context managers.</p>310</div>311</dd></dl>312 313<dl class="py method">314<dt class="sig sig-object py" id="contextvars.ContextVar.reset">315<span class="sig-name descname"><span class="pre">reset</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">token</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#contextvars.ContextVar.reset" title="Link to this definition">¶</a></dt>316<dd><p>Reset the context variable to the value it had before the317<a class="reference internal" href="#contextvars.ContextVar.set" title="contextvars.ContextVar.set"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ContextVar.set()</span></code></a> that created the <em>token</em> was used.</p>318<p>For example:</p>319<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">var</span> <span class="o">=</span> <span class="n">ContextVar</span><span class="p">(</span><span class="s1">&#39;var&#39;</span><span class="p">)</span>320 321<span class="n">token</span> <span class="o">=</span> <span class="n">var</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="s1">&#39;new value&#39;</span><span class="p">)</span>322<span class="c1"># code that uses &#39;var&#39;; var.get() returns &#39;new value&#39;.</span>323<span class="n">var</span><span class="o">.</span><span class="n">reset</span><span class="p">(</span><span class="n">token</span><span class="p">)</span>324 325<span class="c1"># After the reset call the var has no value again, so</span>326<span class="c1"># var.get() would raise a LookupError.</span>327</pre></div>328</div>329<p>The same <em>token</em> cannot be used twice.</p>330</dd></dl>331 332</dd></dl>333 334<dl class="py class">335<dt class="sig sig-object py" id="contextvars.Token">336<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">contextvars.</span></span><span class="sig-name descname"><span class="pre">Token</span></span><a class="headerlink" href="#contextvars.Token" title="Link to this definition">¶</a></dt>337<dd><p><em>Token</em> objects are returned by the <a class="reference internal" href="#contextvars.ContextVar.set" title="contextvars.ContextVar.set"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ContextVar.set()</span></code></a> method.338They can be passed to the <a class="reference internal" href="#contextvars.ContextVar.reset" title="contextvars.ContextVar.reset"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ContextVar.reset()</span></code></a> method to revert339the value of the variable to what it was before the corresponding340<em>set</em>. A single token cannot reset a context variable more than once.</p>341<p>Tokens support the <a class="reference internal" href="../reference/datamodel.html#context-managers"><span class="std std-ref">context manager protocol</span></a>342to automatically reset context variables. See <a class="reference internal" href="#contextvars.ContextVar.set" title="contextvars.ContextVar.set"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ContextVar.set()</span></code></a>.</p>343<div class="versionadded">344<p><span class="versionmodified added">Added in version 3.14: </span>Added support for usage as a context manager.</p>345</div>346<dl class="py attribute">347<dt class="sig sig-object py" id="contextvars.Token.var">348<span class="sig-name descname"><span class="pre">var</span></span><a class="headerlink" href="#contextvars.Token.var" title="Link to this definition">¶</a></dt>349<dd><p>A read-only property.  Points to the <a class="reference internal" href="#contextvars.ContextVar" title="contextvars.ContextVar"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContextVar</span></code></a> object350that created the token.</p>351</dd></dl>352 353<dl class="py attribute">354<dt class="sig sig-object py" id="contextvars.Token.old_value">355<span class="sig-name descname"><span class="pre">old_value</span></span><a class="headerlink" href="#contextvars.Token.old_value" title="Link to this definition">¶</a></dt>356<dd><p>A read-only property.  Set to the value the variable had before357the <a class="reference internal" href="#contextvars.ContextVar.set" title="contextvars.ContextVar.set"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ContextVar.set()</span></code></a> method call that created the token.358It points to <a class="reference internal" href="#contextvars.Token.MISSING" title="contextvars.Token.MISSING"><code class="xref py py-attr docutils literal notranslate"><span class="pre">Token.MISSING</span></code></a> if the variable was not set359before the call.</p>360</dd></dl>361 362<dl class="py attribute">363<dt class="sig sig-object py" id="contextvars.Token.MISSING">364<span class="sig-name descname"><span class="pre">MISSING</span></span><a class="headerlink" href="#contextvars.Token.MISSING" title="Link to this definition">¶</a></dt>365<dd><p>A marker object used by <a class="reference internal" href="#contextvars.Token.old_value" title="contextvars.Token.old_value"><code class="xref py py-attr docutils literal notranslate"><span class="pre">Token.old_value</span></code></a>.</p>366</dd></dl>367 368</dd></dl>369 370</section>371<section id="manual-context-management">372<h2>Manual Context Management<a class="headerlink" href="#manual-context-management" title="Link to this heading">¶</a></h2>373<dl class="py function">374<dt class="sig sig-object py" id="contextvars.copy_context">375<span class="sig-prename descclassname"><span class="pre">contextvars.</span></span><span class="sig-name descname"><span class="pre">copy_context</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#contextvars.copy_context" title="Link to this definition">¶</a></dt>376<dd><p>Returns a copy of the current <a class="reference internal" href="#contextvars.Context" title="contextvars.Context"><code class="xref py py-class docutils literal notranslate"><span class="pre">Context</span></code></a> object.</p>377<p>The following snippet gets a copy of the current context and prints378all variables and their values that are set in it:</p>379<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">ctx</span><span class="p">:</span> <span class="n">Context</span> <span class="o">=</span> <span class="n">copy_context</span><span class="p">()</span>380<span class="nb">print</span><span class="p">(</span><span class="nb">list</span><span class="p">(</span><span class="n">ctx</span><span class="o">.</span><span class="n">items</span><span class="p">()))</span>381</pre></div>382</div>383<p>The function has an <em>O</em>(1) complexity, i.e. works equally fast for384contexts with a few context variables and for contexts that have385a lot of them.</p>386</dd></dl>387 388<dl class="py class">389<dt class="sig sig-object py" id="contextvars.Context">390<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">contextvars.</span></span><span class="sig-name descname"><span class="pre">Context</span></span><a class="headerlink" href="#contextvars.Context" title="Link to this definition">¶</a></dt>391<dd><p>A mapping of <a class="reference internal" href="#contextvars.ContextVar" title="contextvars.ContextVar"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContextVars</span></code></a> to their values.</p>392<p><code class="docutils literal notranslate"><span class="pre">Context()</span></code> creates an empty context with no values in it.393To get a copy of the current context use the394<a class="reference internal" href="#contextvars.copy_context" title="contextvars.copy_context"><code class="xref py py-func docutils literal notranslate"><span class="pre">copy_context()</span></code></a> function.</p>395<p>Each thread has its own effective stack of <code class="xref py py-class docutils literal notranslate"><span class="pre">Context</span></code> objects.  The396<a class="reference internal" href="../glossary.html#term-current-context"><span class="xref std std-term">current context</span></a> is the <code class="xref py py-class docutils literal notranslate"><span class="pre">Context</span></code> object at the top of the397current thread’s stack.  All <code class="xref py py-class docutils literal notranslate"><span class="pre">Context</span></code> objects in the stacks are398considered to be <em>entered</em>.</p>399<p><em>Entering</em> a context, which can be done by calling its <a class="reference internal" href="#contextvars.Context.run" title="contextvars.Context.run"><code class="xref py py-meth docutils literal notranslate"><span class="pre">run()</span></code></a>400method, makes the context the current context by pushing it onto the top of401the current thread’s context stack.</p>402<p><em>Exiting</em> from the current context, which can be done by returning from the403callback passed to the <a class="reference internal" href="#contextvars.Context.run" title="contextvars.Context.run"><code class="xref py py-meth docutils literal notranslate"><span class="pre">run()</span></code></a> method, restores the current404context to what it was before the context was entered by popping the context405off the top of the context stack.</p>406<p>Since each thread has its own context stack, <a class="reference internal" href="#contextvars.ContextVar" title="contextvars.ContextVar"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContextVar</span></code></a> objects407behave in a similar fashion to <a class="reference internal" href="threading.html#threading.local" title="threading.local"><code class="xref py py-func docutils literal notranslate"><span class="pre">threading.local()</span></code></a> when values are408assigned in different threads.</p>409<p>Attempting to enter an already entered context, including contexts entered in410other threads, raises a <a class="reference internal" href="exceptions.html#RuntimeError" title="RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a>.</p>411<p>After exiting a context, it can later be re-entered (from any thread).</p>412<p>Any changes to <a class="reference internal" href="#contextvars.ContextVar" title="contextvars.ContextVar"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContextVar</span></code></a> values via the <a class="reference internal" href="#contextvars.ContextVar.set" title="contextvars.ContextVar.set"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ContextVar.set()</span></code></a>413method are recorded in the current context.  The <a class="reference internal" href="#contextvars.ContextVar.get" title="contextvars.ContextVar.get"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ContextVar.get()</span></code></a>414method returns the value associated with the current context.  Exiting a415context effectively reverts any changes made to context variables while the416context was entered (if needed, the values can be restored by re-entering the417context).</p>418<p>Context implements the <a class="reference internal" href="collections.abc.html#collections.abc.Mapping" title="collections.abc.Mapping"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.abc.Mapping</span></code></a> interface.</p>419<dl class="py method">420<dt class="sig sig-object py" id="contextvars.Context.run">421<span class="sig-name descname"><span class="pre">run</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">callable</span></span></em>, <em class="sig-param"><span class="o"><span class="pre">*</span></span><span class="n"><span class="pre">args</span></span></em>, <em class="sig-param"><span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">kwargs</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#contextvars.Context.run" title="Link to this definition">¶</a></dt>422<dd><p>Enters the Context, executes <code class="docutils literal notranslate"><span class="pre">callable(*args,</span> <span class="pre">**kwargs)</span></code>, then exits the423Context.  Returns <em>callable</em>’s return value, or propagates an exception if424one occurred.</p>425<p>Example:</p>426<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span><span class="w"> </span><span class="nn">contextvars</span>427 428<span class="n">var</span> <span class="o">=</span> <span class="n">contextvars</span><span class="o">.</span><span class="n">ContextVar</span><span class="p">(</span><span class="s1">&#39;var&#39;</span><span class="p">)</span>429<span class="n">var</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="s1">&#39;spam&#39;</span><span class="p">)</span>430<span class="nb">print</span><span class="p">(</span><span class="n">var</span><span class="o">.</span><span class="n">get</span><span class="p">())</span>  <span class="c1"># &#39;spam&#39;</span>431 432<span class="n">ctx</span> <span class="o">=</span> <span class="n">contextvars</span><span class="o">.</span><span class="n">copy_context</span><span class="p">()</span>433 434<span class="k">def</span><span class="w"> </span><span class="nf">main</span><span class="p">():</span>435    <span class="c1"># &#39;var&#39; was set to &#39;spam&#39; before</span>436    <span class="c1"># calling &#39;copy_context()&#39; and &#39;ctx.run(main)&#39;, so:</span>437    <span class="nb">print</span><span class="p">(</span><span class="n">var</span><span class="o">.</span><span class="n">get</span><span class="p">())</span>  <span class="c1"># &#39;spam&#39;</span>438    <span class="nb">print</span><span class="p">(</span><span class="n">ctx</span><span class="p">[</span><span class="n">var</span><span class="p">])</span>  <span class="c1"># &#39;spam&#39;</span>439 440    <span class="n">var</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="s1">&#39;ham&#39;</span><span class="p">)</span>441 442    <span class="c1"># Now, after setting &#39;var&#39; to &#39;ham&#39;:</span>443    <span class="nb">print</span><span class="p">(</span><span class="n">var</span><span class="o">.</span><span class="n">get</span><span class="p">())</span>  <span class="c1"># &#39;ham&#39;</span>444    <span class="nb">print</span><span class="p">(</span><span class="n">ctx</span><span class="p">[</span><span class="n">var</span><span class="p">])</span>  <span class="c1"># &#39;ham&#39;</span>445 446<span class="c1"># Any changes that the &#39;main&#39; function makes to &#39;var&#39;</span>447<span class="c1"># will be contained in &#39;ctx&#39;.</span>448<span class="n">ctx</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="n">main</span><span class="p">)</span>449 450<span class="c1"># The &#39;main()&#39; function was run in the &#39;ctx&#39; context,</span>451<span class="c1"># so changes to &#39;var&#39; are contained in it:</span>452<span class="nb">print</span><span class="p">(</span><span class="n">ctx</span><span class="p">[</span><span class="n">var</span><span class="p">])</span>  <span class="c1"># &#39;ham&#39;</span>453 454<span class="c1"># However, outside of &#39;ctx&#39;, &#39;var&#39; is still set to &#39;spam&#39;:</span>455<span class="nb">print</span><span class="p">(</span><span class="n">var</span><span class="o">.</span><span class="n">get</span><span class="p">())</span>  <span class="c1"># &#39;spam&#39;</span>456</pre></div>457</div>458</dd></dl>459 460<dl class="py method">461<dt class="sig sig-object py" id="contextvars.Context.copy">462<span class="sig-name descname"><span class="pre">copy</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#contextvars.Context.copy" title="Link to this definition">¶</a></dt>463<dd><p>Return a shallow copy of the context object.</p>464</dd></dl>465 466<dl class="describe">467<dt class="sig sig-object">468<span class="sig-name descname"><span class="pre">var</span> <span class="pre">in</span> <span class="pre">context</span></span></dt>469<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the <em>context</em> has a value for <em>var</em> set;470return <code class="docutils literal notranslate"><span class="pre">False</span></code> otherwise.</p>471</dd></dl>472 473<dl class="describe">474<dt class="sig sig-object">475<span class="sig-name descname"><span class="pre">context[var]</span></span></dt>476<dd><p>Return the value of the <em>var</em> <a class="reference internal" href="#contextvars.ContextVar" title="contextvars.ContextVar"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContextVar</span></code></a> variable.477If the variable is not set in the context object, a478<a class="reference internal" href="exceptions.html#KeyError" title="KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> is raised.</p>479</dd></dl>480 481<dl class="py method">482<dt class="sig sig-object py" id="contextvars.Context.get">483<span class="sig-name descname"><span class="pre">get</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">var</span></span></em><span class="optional">[</span>, <em class="sig-param"><span class="n"><span class="pre">default</span></span></em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#contextvars.Context.get" title="Link to this definition">¶</a></dt>484<dd><p>Return the value for <em>var</em> if <em>var</em> has the value in the context485object.  Return <em>default</em> otherwise.  If <em>default</em> is not given,486return <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>487</dd></dl>488 489<dl class="describe">490<dt class="sig sig-object">491<span class="sig-name descname"><span class="pre">iter(context)</span></span></dt>492<dd><p>Return an iterator over the variables stored in the context493object.</p>494</dd></dl>495 496<dl class="describe">497<dt class="sig sig-object">498<span class="sig-name descname"><span class="pre">len(proxy)</span></span></dt>499<dd><p>Return the number of variables set in the context object.</p>500</dd></dl>501 502<dl class="py method">503<dt class="sig sig-object py" id="contextvars.Context.keys">504<span class="sig-name descname"><span class="pre">keys</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#contextvars.Context.keys" title="Link to this definition">¶</a></dt>505<dd><p>Return a list of all variables in the context object.</p>506</dd></dl>507 508<dl class="py method">509<dt class="sig sig-object py" id="contextvars.Context.values">510<span class="sig-name descname"><span class="pre">values</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#contextvars.Context.values" title="Link to this definition">¶</a></dt>511<dd><p>Return a list of all variables’ values in the context object.</p>512</dd></dl>513 514<dl class="py method">515<dt class="sig sig-object py" id="contextvars.Context.items">516<span class="sig-name descname"><span class="pre">items</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#contextvars.Context.items" title="Link to this definition">¶</a></dt>517<dd><p>Return a list of 2-tuples containing all variables and their518values in the context object.</p>519</dd></dl>520 521</dd></dl>522 523</section>524<section id="asyncio-support">525<h2>asyncio support<a class="headerlink" href="#asyncio-support" title="Link to this heading">¶</a></h2>526<p>Context variables are natively supported in <a class="reference internal" href="asyncio.html#module-asyncio" title="asyncio: Asynchronous I/O."><code class="xref py py-mod docutils literal notranslate"><span class="pre">asyncio</span></code></a> and are527ready to be used without any extra configuration.  For example, here528is a simple echo server, that uses a context variable to make the529address of a remote client available in the Task that handles that530client:</p>531<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span><span class="w"> </span><span class="nn">asyncio</span>532<span class="kn">import</span><span class="w"> </span><span class="nn">contextvars</span>533 534<span class="n">client_addr_var</span> <span class="o">=</span> <span class="n">contextvars</span><span class="o">.</span><span class="n">ContextVar</span><span class="p">(</span><span class="s1">&#39;client_addr&#39;</span><span class="p">)</span>535 536<span class="k">def</span><span class="w"> </span><span class="nf">render_goodbye</span><span class="p">():</span>537    <span class="c1"># The address of the currently handled client can be accessed</span>538    <span class="c1"># without passing it explicitly to this function.</span>539 540    <span class="n">client_addr</span> <span class="o">=</span> <span class="n">client_addr_var</span><span class="o">.</span><span class="n">get</span><span class="p">()</span>541    <span class="k">return</span> <span class="sa">f</span><span class="s1">&#39;Good bye, client @ </span><span class="si">{</span><span class="n">client_addr</span><span class="si">}</span><span class="se">\r\n</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">encode</span><span class="p">()</span>542 543<span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">handle_request</span><span class="p">(</span><span class="n">reader</span><span class="p">,</span> <span class="n">writer</span><span class="p">):</span>544    <span class="n">addr</span> <span class="o">=</span> <span class="n">writer</span><span class="o">.</span><span class="n">transport</span><span class="o">.</span><span class="n">get_extra_info</span><span class="p">(</span><span class="s1">&#39;socket&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">getpeername</span><span class="p">()</span>545    <span class="n">client_addr_var</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="n">addr</span><span class="p">)</span>546 547    <span class="c1"># In any code that we call, it is now possible to get the</span>548    <span class="c1"># client&#39;s address by calling &#39;client_addr_var.get()&#39;.</span>549 550    <span class="k">while</span> <span class="kc">True</span><span class="p">:</span>551        <span class="n">line</span> <span class="o">=</span> <span class="k">await</span> <span class="n">reader</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>552        <span class="nb">print</span><span class="p">(</span><span class="n">line</span><span class="p">)</span>553        <span class="k">if</span> <span class="ow">not</span> <span class="n">line</span><span class="o">.</span><span class="n">strip</span><span class="p">():</span>554            <span class="k">break</span>555 556    <span class="n">writer</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="sa">b</span><span class="s1">&#39;HTTP/1.1 200 OK</span><span class="se">\r\n</span><span class="s1">&#39;</span><span class="p">)</span>  <span class="c1"># status line</span>557    <span class="n">writer</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="sa">b</span><span class="s1">&#39;</span><span class="se">\r\n</span><span class="s1">&#39;</span><span class="p">)</span>  <span class="c1"># headers</span>558    <span class="n">writer</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">render_goodbye</span><span class="p">())</span>  <span class="c1"># body</span>559    <span class="n">writer</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>560 561<span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">main</span><span class="p">():</span>562    <span class="n">srv</span> <span class="o">=</span> <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">start_server</span><span class="p">(</span>563        <span class="n">handle_request</span><span class="p">,</span> <span class="s1">&#39;127.0.0.1&#39;</span><span class="p">,</span> <span class="mi">8081</span><span class="p">)</span>564 565    <span class="k">async</span> <span class="k">with</span> <span class="n">srv</span><span class="p">:</span>566        <span class="k">await</span> <span class="n">srv</span><span class="o">.</span><span class="n">serve_forever</span><span class="p">()</span>567 568<span class="n">asyncio</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="n">main</span><span class="p">())</span>569 570<span class="c1"># To test it you can use telnet or curl:</span>571<span class="c1">#     telnet 127.0.0.1 8081</span>572<span class="c1">#     curl 127.0.0.1:8081</span>573</pre></div>574</div>575</section>576</section>577 578 579            <div class="clearer"></div>580          </div>581        </div>582      </div>583      <div class="sphinxsidebar" role="navigation" aria-label="Main">584        <div class="sphinxsidebarwrapper">585  <div>586    <h3><a href="../contents.html">Table of Contents</a></h3>587    <ul>588<li><a class="reference internal" href="#"><code class="xref py py-mod docutils literal notranslate"><span class="pre">contextvars</span></code> — Context Variables</a><ul>589<li><a class="reference internal" href="#context-variables">Context Variables</a></li>590<li><a class="reference internal" href="#manual-context-management">Manual Context Management</a></li>591<li><a class="reference internal" href="#asyncio-support">asyncio support</a></li>592</ul>593</li>594</ul>595 596  </div>597  <div>598    <h4>Previous topic</h4>599    <p class="topless"><a href="queue.html"600                          title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">queue</span></code> — A synchronized queue class</a></p>601  </div>602  <div>603    <h4>Next topic</h4>604    <p class="topless"><a href="_thread.html"605                          title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">_thread</span></code> — Low-level threading API</a></p>606  </div>607  <script>608    document.addEventListener('DOMContentLoaded', () => {609        const title = document.querySelector('meta[property="og:title"]').content;610        const elements = document.querySelectorAll('.improvepage');611        const pageurl = window.location.href.split('?')[0];612        elements.forEach(element => {613            const url = new URL(element.href.split('?')[0].replace("-nojs", ""));614            url.searchParams.set('pagetitle', title);615            url.searchParams.set('pageurl', pageurl);616            url.searchParams.set('pagesource', "library/contextvars.rst");617            element.href = url.toString();618        });619    });620  </script>621  <div role="note" aria-label="source link">622    <h3>This page</h3>623    <ul class="this-page-menu">624      <li><a href="../bugs.html">Report a bug</a></li>625      <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li>626      <li>627        <a href="https://github.com/python/cpython/blob/main/Doc/library/contextvars.rst?plain=1"628            rel="nofollow">Show source629        </a>630      </li>631      632    </ul>633  </div>634        </div>635<div id="sidebarbutton" title="Collapse sidebar">636<span>«</span>637</div>638 639      </div>640      <div class="clearer"></div>641    </div>  642    <div class="related" role="navigation" aria-label="Related">643      <h3>Navigation</h3>644      <ul>645        <li class="right" style="margin-right: 10px">646          <a href="../genindex.html" title="General Index"647             >index</a></li>648        <li class="right" >649          <a href="../py-modindex.html" title="Python Module Index"650             >modules</a> |</li>651        <li class="right" >652          <a href="_thread.html" title="_thread — Low-level threading API"653             >next</a> |</li>654        <li class="right" >655          <a href="queue.html" title="queue — A synchronized queue class"656             >previous</a> |</li>657 658          <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li>659          <li><a href="https://www.python.org/">Python</a> &#187;</li>660          <li class="switchers">661            <div class="language_switcher_placeholder"></div>662            <div class="version_switcher_placeholder"></div>663          </li>664          <li>665              666          </li>667    <li id="cpython-language-and-version">668      <a href="../index.html">3.15.0a6 Documentation</a> &#187;669    </li>670 671          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>672          <li class="nav-item nav-item-2"><a href="concurrency.html" >Concurrent Execution</a> &#187;</li>673        <li class="nav-item nav-item-this"><a href=""><code class="xref py py-mod docutils literal notranslate"><span class="pre">contextvars</span></code> — Context Variables</a></li>674                <li class="right">675                    676 677    <div class="inline-search" role="search">678        <form class="inline-search" action="../search.html" method="get">679          <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box">680          <input type="submit" value="Go">681        </form>682    </div>683                     |684                </li>685            <li class="right">686<label class="theme-selector-label">687    Theme688    <select class="theme-selector" oninput="activateTheme(this.value)">689        <option value="auto" selected>Auto</option>690        <option value="light">Light</option>691        <option value="dark">Dark</option>692    </select>693</label> |</li>694            695      </ul>696    </div>  697    <div class="footer">698    &copy; <a href="../copyright.html">Copyright</a> 2001 Python Software Foundation.699    <br>700    This page is licensed under the Python Software Foundation License Version 2.701    <br>702    Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.703    <br>704    705      See <a href="/license.html">History and License</a> for more information.<br>706    707    708    <br>709 710    The Python Software Foundation is a non-profit corporation.711<a href="https://www.python.org/psf/donations/">Please donate.</a>712<br>713    <br>714      Last updated on Mar 10, 2026 (08:58 UTC).715    716      <a href="/bugs.html">Found a bug</a>?717    718    <br>719 720    Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3.721    </div>722 723  </body>724</html>