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

636 lines
41KB

  1. <!DOCTYPE html>
  2. <html lang="en" data-content_root="../">
  3. <head>
  4. <meta charset="utf-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" />
  6. <meta property="og:title" content="contextvars — Context Variables" />
  7. <meta property="og:type" content="website" />
  8. <meta property="og:url" content="https://docs.python.org/3/library/contextvars.html" />
  9. <meta property="og:site_name" content="Python documentation" />
  10. <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..." />
  11. <meta property="og:image" content="https://docs.python.org/3/_static/og-image.png" />
  12. <meta property="og:image:alt" content="Python documentation" />
  13. <meta name="description" content="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..." />
  14. <meta property="og:image:width" content="200" />
  15. <meta property="og:image:height" content="200" />
  16. <meta name="theme-color" content="#3776ab" />
  17. <title>contextvars — Context Variables &#8212; Python 3.12.3 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">
  18. <link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=80d5e7a1" />
  19. <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=bb723527" />
  20. <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=b20cc3f5" />
  21. <script src="../_static/documentation_options.js?v=2c828074"></script>
  22. <script src="../_static/doctools.js?v=888ff710"></script>
  23. <script src="../_static/sphinx_highlight.js?v=dc90522c"></script>
  24. <script src="../_static/sidebar.js"></script>
  25. <link rel="search" type="application/opensearchdescription+xml"
  26. title="Search within Python 3.12.3 documentation"
  27. href="../_static/opensearch.xml"/>
  28. <link rel="author" title="About these documents" href="../about.html" />
  29. <link rel="index" title="Index" href="../genindex.html" />
  30. <link rel="search" title="Search" href="../search.html" />
  31. <link rel="copyright" title="Copyright" href="../copyright.html" />
  32. <link rel="next" title="_thread — Low-level threading API" href="_thread.html" />
  33. <link rel="prev" title="queue — A synchronized queue class" href="queue.html" />
  34. <link rel="canonical" href="https://docs.python.org/3/library/contextvars.html" />
  35. <style>
  36. @media only screen {
  37. table.full-width-table {
  38. width: 100%;
  39. }
  40. }
  41. </style>
  42. <link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">
  43. <link rel="shortcut icon" type="image/png" href="../_static/py.svg" />
  44. <script type="text/javascript" src="../_static/copybutton.js"></script>
  45. <script type="text/javascript" src="../_static/menu.js"></script>
  46. <script type="text/javascript" src="../_static/search-focus.js"></script>
  47. <script type="text/javascript" src="../_static/themetoggle.js"></script>
  48. </head>
  49. <body>
  50. <div class="mobile-nav">
  51. <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"
  52. aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu" />
  53. <nav class="nav-content" role="navigation">
  54. <label for="menuToggler" class="toggler__label">
  55. <span></span>
  56. </label>
  57. <span class="nav-items-wrapper">
  58. <a href="https://www.python.org/" class="nav-logo">
  59. <img src="../_static/py.svg" alt="Python logo"/>
  60. </a>
  61. <span class="version_switcher_placeholder"></span>
  62. <form role="search" class="search" action="../search.html" method="get">
  63. <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">
  64. <path fill-rule="nonzero" fill="currentColor" d="M15.5 14h-.79l-.28-.27a6.5 6.5 0 001.48-5.34c-.47-2.78-2.79-5-5.59-5.34a6.505 6.505 0 00-7.27 7.27c.34 2.8 2.56 5.12 5.34 5.59a6.5 6.5 0 005.34-1.48l.27.28v.79l4.25 4.25c.41.41 1.08.41 1.49 0 .41-.41.41-1.08 0-1.49L15.5 14zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"></path>
  65. </svg>
  66. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
  67. <input type="submit" value="Go"/>
  68. </form>
  69. </span>
  70. </nav>
  71. <div class="menu-wrapper">
  72. <nav class="menu" role="navigation" aria-label="main navigation">
  73. <div class="language_switcher_placeholder"></div>
  74. <label class="theme-selector-label">
  75. Theme
  76. <select class="theme-selector" oninput="activateTheme(this.value)">
  77. <option value="auto" selected>Auto</option>
  78. <option value="light">Light</option>
  79. <option value="dark">Dark</option>
  80. </select>
  81. </label>
  82. <div>
  83. <h3><a href="../contents.html">Table of Contents</a></h3>
  84. <ul>
  85. <li><a class="reference internal" href="#"><code class="xref py py-mod docutils literal notranslate"><span class="pre">contextvars</span></code> — Context Variables</a><ul>
  86. <li><a class="reference internal" href="#context-variables">Context Variables</a></li>
  87. <li><a class="reference internal" href="#manual-context-management">Manual Context Management</a></li>
  88. <li><a class="reference internal" href="#asyncio-support">asyncio support</a></li>
  89. </ul>
  90. </li>
  91. </ul>
  92. </div>
  93. <div>
  94. <h4>Previous topic</h4>
  95. <p class="topless"><a href="queue.html"
  96. title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">queue</span></code> — A synchronized queue class</a></p>
  97. </div>
  98. <div>
  99. <h4>Next topic</h4>
  100. <p class="topless"><a href="_thread.html"
  101. title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">_thread</span></code> — Low-level threading API</a></p>
  102. </div>
  103. <div role="note" aria-label="source link">
  104. <h3>This Page</h3>
  105. <ul class="this-page-menu">
  106. <li><a href="../bugs.html">Report a Bug</a></li>
  107. <li>
  108. <a href="https://github.com/python/cpython/blob/main/Doc/library/contextvars.rst"
  109. rel="nofollow">Show Source
  110. </a>
  111. </li>
  112. </ul>
  113. </div>
  114. </nav>
  115. </div>
  116. </div>
  117. <div class="related" role="navigation" aria-label="related navigation">
  118. <h3>Navigation</h3>
  119. <ul>
  120. <li class="right" style="margin-right: 10px">
  121. <a href="../genindex.html" title="General Index"
  122. accesskey="I">index</a></li>
  123. <li class="right" >
  124. <a href="../py-modindex.html" title="Python Module Index"
  125. >modules</a> |</li>
  126. <li class="right" >
  127. <a href="_thread.html" title="_thread — Low-level threading API"
  128. accesskey="N">next</a> |</li>
  129. <li class="right" >
  130. <a href="queue.html" title="queue — A synchronized queue class"
  131. accesskey="P">previous</a> |</li>
  132. <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  133. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  134. <li class="switchers">
  135. <div class="language_switcher_placeholder"></div>
  136. <div class="version_switcher_placeholder"></div>
  137. </li>
  138. <li>
  139. </li>
  140. <li id="cpython-language-and-version">
  141. <a href="../index.html">3.12.3 Documentation</a> &#187;
  142. </li>
  143. <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
  144. <li class="nav-item nav-item-2"><a href="concurrency.html" accesskey="U">Concurrent Execution</a> &#187;</li>
  145. <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>
  146. <li class="right">
  147. <div class="inline-search" role="search">
  148. <form class="inline-search" action="../search.html" method="get">
  149. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
  150. <input type="submit" value="Go" />
  151. </form>
  152. </div>
  153. |
  154. </li>
  155. <li class="right">
  156. <label class="theme-selector-label">
  157. Theme
  158. <select class="theme-selector" oninput="activateTheme(this.value)">
  159. <option value="auto" selected>Auto</option>
  160. <option value="light">Light</option>
  161. <option value="dark">Dark</option>
  162. </select>
  163. </label> |</li>
  164. </ul>
  165. </div>
  166. <div class="document">
  167. <div class="documentwrapper">
  168. <div class="bodywrapper">
  169. <div class="body" role="main">
  170. <section id="module-contextvars">
  171. <span id="contextvars-context-variables"></span><h1><a class="reference internal" href="#module-contextvars" title="contextvars: Context Variables"><code class="xref py py-mod docutils literal notranslate"><span class="pre">contextvars</span></code></a> — Context Variables<a class="headerlink" href="#module-contextvars" title="Link to this heading">¶</a></h1>
  172. <hr class="docutils" />
  173. <p>This module provides APIs to manage, store, and access context-local
  174. state. 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 declare
  175. and 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>
  176. function 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 to
  177. manage the current context in asynchronous frameworks.</p>
  178. <p>Context managers that have state should use Context Variables
  179. instead 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 from
  180. bleeding to other code unexpectedly, when used in concurrent code.</p>
  181. <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>
  182. <div class="versionadded">
  183. <p><span class="versionmodified added">New in version 3.7.</span></p>
  184. </div>
  185. <section id="context-variables">
  186. <h2>Context Variables<a class="headerlink" href="#context-variables" title="Link to this heading">¶</a></h2>
  187. <dl class="py class">
  188. <dt class="sig sig-object py" id="contextvars.ContextVar">
  189. <em class="property"><span class="pre">class</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>
  190. <dd><p>This class is used to declare a new Context Variable, e.g.:</p>
  191. <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>
  192. </pre></div>
  193. </div>
  194. <p>The required <em>name</em> parameter is used for introspection and debug
  195. purposes.</p>
  196. <p>The optional keyword-only <em>default</em> parameter is returned by
  197. <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 found
  198. in the current context.</p>
  199. <p><strong>Important:</strong> Context Variables should be created at the top module
  200. level 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 strong
  201. references to context variables which prevents context variables
  202. from being properly garbage collected.</p>
  203. <dl class="py attribute">
  204. <dt class="sig sig-object py" id="contextvars.ContextVar.name">
  205. <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>
  206. <dd><p>The name of the variable. This is a read-only property.</p>
  207. <div class="versionadded">
  208. <p><span class="versionmodified added">New in version 3.7.1.</span></p>
  209. </div>
  210. </dd></dl>
  211. <dl class="py method">
  212. <dt class="sig sig-object py" id="contextvars.ContextVar.get">
  213. <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>
  214. <dd><p>Return a value for the context variable for the current context.</p>
  215. <p>If there is no value for the variable in the current context,
  216. the method will:</p>
  217. <ul class="simple">
  218. <li><p>return the value of the <em>default</em> argument of the method,
  219. if provided; or</p></li>
  220. <li><p>return the default value for the context variable,
  221. if it was created with one; or</p></li>
  222. <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>
  223. </ul>
  224. </dd></dl>
  225. <dl class="py method">
  226. <dt class="sig sig-object py" id="contextvars.ContextVar.set">
  227. <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>
  228. <dd><p>Call to set a new value for the context variable in the current
  229. context.</p>
  230. <p>The required <em>value</em> argument is the new value for the context
  231. variable.</p>
  232. <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 used
  233. to restore the variable to its previous value via the
  234. <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>
  235. </dd></dl>
  236. <dl class="py method">
  237. <dt class="sig sig-object py" id="contextvars.ContextVar.reset">
  238. <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>
  239. <dd><p>Reset the context variable to the value it had before the
  240. <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>
  241. <p>For example:</p>
  242. <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>
  243. <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>
  244. <span class="c1"># code that uses &#39;var&#39;; var.get() returns &#39;new value&#39;.</span>
  245. <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>
  246. <span class="c1"># After the reset call the var has no value again, so</span>
  247. <span class="c1"># var.get() would raise a LookupError.</span>
  248. </pre></div>
  249. </div>
  250. </dd></dl>
  251. </dd></dl>
  252. <dl class="py class">
  253. <dt class="sig sig-object py" id="contextvars.Token">
  254. <em class="property"><span class="pre">class</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>
  255. <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.
  256. They 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 revert
  257. the value of the variable to what it was before the corresponding
  258. <em>set</em>.</p>
  259. <dl class="py attribute">
  260. <dt class="sig sig-object py" id="contextvars.Token.var">
  261. <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>
  262. <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> object
  263. that created the token.</p>
  264. </dd></dl>
  265. <dl class="py attribute">
  266. <dt class="sig sig-object py" id="contextvars.Token.old_value">
  267. <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>
  268. <dd><p>A read-only property. Set to the value the variable had before
  269. 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 call that created the token.
  270. It 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 set
  271. before the call.</p>
  272. </dd></dl>
  273. <dl class="py attribute">
  274. <dt class="sig sig-object py" id="contextvars.Token.MISSING">
  275. <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>
  276. <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>
  277. </dd></dl>
  278. </dd></dl>
  279. </section>
  280. <section id="manual-context-management">
  281. <h2>Manual Context Management<a class="headerlink" href="#manual-context-management" title="Link to this heading">¶</a></h2>
  282. <dl class="py function">
  283. <dt class="sig sig-object py" id="contextvars.copy_context">
  284. <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>
  285. <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>
  286. <p>The following snippet gets a copy of the current context and prints
  287. all variables and their values that are set in it:</p>
  288. <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>
  289. <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>
  290. </pre></div>
  291. </div>
  292. <p>The function has an <em>O</em>(1) complexity, i.e. works equally fast for
  293. contexts with a few context variables and for contexts that have
  294. a lot of them.</p>
  295. </dd></dl>
  296. <dl class="py class">
  297. <dt class="sig sig-object py" id="contextvars.Context">
  298. <em class="property"><span class="pre">class</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>
  299. <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>
  300. <p><code class="docutils literal notranslate"><span class="pre">Context()</span></code> creates an empty context with no values in it.
  301. To get a copy of the current context use the
  302. <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>
  303. <p>Every thread will have a different top-level <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>
  304. object. This means that a <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> object behaves in a similar
  305. 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 are assigned in different
  306. threads.</p>
  307. <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>
  308. <dl class="py method">
  309. <dt class="sig sig-object py" id="contextvars.Context.run">
  310. <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>
  311. <dd><p>Execute <code class="docutils literal notranslate"><span class="pre">callable(*args,</span> <span class="pre">**kwargs)</span></code> code in the context object
  312. the <em>run</em> method is called on. Return the result of the execution
  313. or propagate an exception if one occurred.</p>
  314. <p>Any changes to any context variables that <em>callable</em> makes will
  315. be contained in the context object:</p>
  316. <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>
  317. <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>
  318. <span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
  319. <span class="c1"># &#39;var&#39; was set to &#39;spam&#39; before</span>
  320. <span class="c1"># calling &#39;copy_context()&#39; and &#39;ctx.run(main)&#39;, so:</span>
  321. <span class="c1"># var.get() == ctx[var] == &#39;spam&#39;</span>
  322. <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>
  323. <span class="c1"># Now, after setting &#39;var&#39; to &#39;ham&#39;:</span>
  324. <span class="c1"># var.get() == ctx[var] == &#39;ham&#39;</span>
  325. <span class="n">ctx</span> <span class="o">=</span> <span class="n">copy_context</span><span class="p">()</span>
  326. <span class="c1"># Any changes that the &#39;main&#39; function makes to &#39;var&#39;</span>
  327. <span class="c1"># will be contained in &#39;ctx&#39;.</span>
  328. <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>
  329. <span class="c1"># The &#39;main()&#39; function was run in the &#39;ctx&#39; context,</span>
  330. <span class="c1"># so changes to &#39;var&#39; are contained in it:</span>
  331. <span class="c1"># ctx[var] == &#39;ham&#39;</span>
  332. <span class="c1"># However, outside of &#39;ctx&#39;, &#39;var&#39; is still set to &#39;spam&#39;:</span>
  333. <span class="c1"># var.get() == &#39;spam&#39;</span>
  334. </pre></div>
  335. </div>
  336. <p>The method 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> when called on the same
  337. context object from more than one OS thread, or when called
  338. recursively.</p>
  339. </dd></dl>
  340. <dl class="py method">
  341. <dt class="sig sig-object py" id="contextvars.Context.copy">
  342. <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>
  343. <dd><p>Return a shallow copy of the context object.</p>
  344. </dd></dl>
  345. <dl class="describe">
  346. <dt class="sig sig-object">
  347. <span class="sig-name descname"><span class="pre">var</span> <span class="pre">in</span> <span class="pre">context</span></span></dt>
  348. <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;
  349. return <code class="docutils literal notranslate"><span class="pre">False</span></code> otherwise.</p>
  350. </dd></dl>
  351. <dl class="describe">
  352. <dt class="sig sig-object">
  353. <span class="sig-name descname"><span class="pre">context[var]</span></span></dt>
  354. <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.
  355. If the variable is not set in the context object, a
  356. <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>
  357. </dd></dl>
  358. <dl class="py method">
  359. <dt class="sig sig-object py" id="contextvars.Context.get">
  360. <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>
  361. <dd><p>Return the value for <em>var</em> if <em>var</em> has the value in the context
  362. object. Return <em>default</em> otherwise. If <em>default</em> is not given,
  363. return <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
  364. </dd></dl>
  365. <dl class="describe">
  366. <dt class="sig sig-object">
  367. <span class="sig-name descname"><span class="pre">iter(context)</span></span></dt>
  368. <dd><p>Return an iterator over the variables stored in the context
  369. object.</p>
  370. </dd></dl>
  371. <dl class="describe">
  372. <dt class="sig sig-object">
  373. <span class="sig-name descname"><span class="pre">len(proxy)</span></span></dt>
  374. <dd><p>Return the number of variables set in the context object.</p>
  375. </dd></dl>
  376. <dl class="py method">
  377. <dt class="sig sig-object py" id="contextvars.Context.keys">
  378. <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>
  379. <dd><p>Return a list of all variables in the context object.</p>
  380. </dd></dl>
  381. <dl class="py method">
  382. <dt class="sig sig-object py" id="contextvars.Context.values">
  383. <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>
  384. <dd><p>Return a list of all variables’ values in the context object.</p>
  385. </dd></dl>
  386. <dl class="py method">
  387. <dt class="sig sig-object py" id="contextvars.Context.items">
  388. <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>
  389. <dd><p>Return a list of 2-tuples containing all variables and their
  390. values in the context object.</p>
  391. </dd></dl>
  392. </dd></dl>
  393. </section>
  394. <section id="asyncio-support">
  395. <h2>asyncio support<a class="headerlink" href="#asyncio-support" title="Link to this heading">¶</a></h2>
  396. <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 are
  397. ready to be used without any extra configuration. For example, here
  398. is a simple echo server, that uses a context variable to make the
  399. address of a remote client available in the Task that handles that
  400. client:</p>
  401. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">asyncio</span>
  402. <span class="kn">import</span> <span class="nn">contextvars</span>
  403. <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>
  404. <span class="k">def</span> <span class="nf">render_goodbye</span><span class="p">():</span>
  405. <span class="c1"># The address of the currently handled client can be accessed</span>
  406. <span class="c1"># without passing it explicitly to this function.</span>
  407. <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>
  408. <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">\n</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">encode</span><span class="p">()</span>
  409. <span class="k">async</span> <span class="k">def</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>
  410. <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>
  411. <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>
  412. <span class="c1"># In any code that we call is now possible to get</span>
  413. <span class="c1"># client&#39;s address by calling &#39;client_addr_var.get()&#39;.</span>
  414. <span class="k">while</span> <span class="kc">True</span><span class="p">:</span>
  415. <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>
  416. <span class="nb">print</span><span class="p">(</span><span class="n">line</span><span class="p">)</span>
  417. <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>
  418. <span class="k">break</span>
  419. <span class="n">writer</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">line</span><span class="p">)</span>
  420. <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>
  421. <span class="n">writer</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
  422. <span class="k">async</span> <span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
  423. <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>
  424. <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>
  425. <span class="k">async</span> <span class="k">with</span> <span class="n">srv</span><span class="p">:</span>
  426. <span class="k">await</span> <span class="n">srv</span><span class="o">.</span><span class="n">serve_forever</span><span class="p">()</span>
  427. <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>
  428. <span class="c1"># To test it you can use telnet:</span>
  429. <span class="c1"># telnet 127.0.0.1 8081</span>
  430. </pre></div>
  431. </div>
  432. </section>
  433. </section>
  434. <div class="clearer"></div>
  435. </div>
  436. </div>
  437. </div>
  438. <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
  439. <div class="sphinxsidebarwrapper">
  440. <div>
  441. <h3><a href="../contents.html">Table of Contents</a></h3>
  442. <ul>
  443. <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>
  444. <li><a class="reference internal" href="#context-variables">Context Variables</a></li>
  445. <li><a class="reference internal" href="#manual-context-management">Manual Context Management</a></li>
  446. <li><a class="reference internal" href="#asyncio-support">asyncio support</a></li>
  447. </ul>
  448. </li>
  449. </ul>
  450. </div>
  451. <div>
  452. <h4>Previous topic</h4>
  453. <p class="topless"><a href="queue.html"
  454. title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">queue</span></code> — A synchronized queue class</a></p>
  455. </div>
  456. <div>
  457. <h4>Next topic</h4>
  458. <p class="topless"><a href="_thread.html"
  459. title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">_thread</span></code> — Low-level threading API</a></p>
  460. </div>
  461. <div role="note" aria-label="source link">
  462. <h3>This Page</h3>
  463. <ul class="this-page-menu">
  464. <li><a href="../bugs.html">Report a Bug</a></li>
  465. <li>
  466. <a href="https://github.com/python/cpython/blob/main/Doc/library/contextvars.rst"
  467. rel="nofollow">Show Source
  468. </a>
  469. </li>
  470. </ul>
  471. </div>
  472. </div>
  473. <div id="sidebarbutton" title="Collapse sidebar">
  474. <span>«</span>
  475. </div>
  476. </div>
  477. <div class="clearer"></div>
  478. </div>
  479. <div class="related" role="navigation" aria-label="related navigation">
  480. <h3>Navigation</h3>
  481. <ul>
  482. <li class="right" style="margin-right: 10px">
  483. <a href="../genindex.html" title="General Index"
  484. >index</a></li>
  485. <li class="right" >
  486. <a href="../py-modindex.html" title="Python Module Index"
  487. >modules</a> |</li>
  488. <li class="right" >
  489. <a href="_thread.html" title="_thread — Low-level threading API"
  490. >next</a> |</li>
  491. <li class="right" >
  492. <a href="queue.html" title="queue — A synchronized queue class"
  493. >previous</a> |</li>
  494. <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  495. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  496. <li class="switchers">
  497. <div class="language_switcher_placeholder"></div>
  498. <div class="version_switcher_placeholder"></div>
  499. </li>
  500. <li>
  501. </li>
  502. <li id="cpython-language-and-version">
  503. <a href="../index.html">3.12.3 Documentation</a> &#187;
  504. </li>
  505. <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
  506. <li class="nav-item nav-item-2"><a href="concurrency.html" >Concurrent Execution</a> &#187;</li>
  507. <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>
  508. <li class="right">
  509. <div class="inline-search" role="search">
  510. <form class="inline-search" action="../search.html" method="get">
  511. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
  512. <input type="submit" value="Go" />
  513. </form>
  514. </div>
  515. |
  516. </li>
  517. <li class="right">
  518. <label class="theme-selector-label">
  519. Theme
  520. <select class="theme-selector" oninput="activateTheme(this.value)">
  521. <option value="auto" selected>Auto</option>
  522. <option value="light">Light</option>
  523. <option value="dark">Dark</option>
  524. </select>
  525. </label> |</li>
  526. </ul>
  527. </div>
  528. <div class="footer">
  529. &copy;
  530. <a href="../copyright.html">
  531. Copyright
  532. </a>
  533. 2001-2024, Python Software Foundation.
  534. <br />
  535. This page is licensed under the Python Software Foundation License Version 2.
  536. <br />
  537. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
  538. <br />
  539. See <a href="/license.html">History and License</a> for more information.<br />
  540. <br />
  541. The Python Software Foundation is a non-profit corporation.
  542. <a href="https://www.python.org/psf/donations/">Please donate.</a>
  543. <br />
  544. <br />
  545. Last updated on Apr 09, 2024 (13:47 UTC).
  546. <a href="/bugs.html">Found a bug</a>?
  547. <br />
  548. Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 7.2.6.
  549. </div>
  550. </body>
  551. </html>
上海开阖软件有限公司 沪ICP备12045867号-1