summaryrefslogtreecommitdiff
path: root/devdocs/python~3.12/library%2Fcontextvars.html
diff options
context:
space:
mode:
authorCraig Jennings <c@cjennings.net>2024-04-07 13:41:34 -0500
committerCraig Jennings <c@cjennings.net>2024-04-07 13:41:34 -0500
commit754bbf7a25a8dda49b5d08ef0d0443bbf5af0e36 (patch)
treef1190704f78f04a2b0b4c977d20fe96a828377f1 /devdocs/python~3.12/library%2Fcontextvars.html
new repository
Diffstat (limited to 'devdocs/python~3.12/library%2Fcontextvars.html')
-rw-r--r--devdocs/python~3.12/library%2Fcontextvars.html145
1 files changed, 145 insertions, 0 deletions
diff --git a/devdocs/python~3.12/library%2Fcontextvars.html b/devdocs/python~3.12/library%2Fcontextvars.html
new file mode 100644
index 00000000..d96744eb
--- /dev/null
+++ b/devdocs/python~3.12/library%2Fcontextvars.html
@@ -0,0 +1,145 @@
+ <span id="contextvars-context-variables"></span><h1>contextvars — Context Variables</h1> <p>This module provides APIs to manage, store, and access context-local state. The <a class="reference internal" href="#contextvars.ContextVar" title="contextvars.ContextVar"><code>ContextVar</code></a> class is used to declare and work with <em>Context Variables</em>. The <a class="reference internal" href="#contextvars.copy_context" title="contextvars.copy_context"><code>copy_context()</code></a> function and the <a class="reference internal" href="#contextvars.Context" title="contextvars.Context"><code>Context</code></a> class should be used to manage the current context in asynchronous frameworks.</p> <p>Context managers that have state should use Context Variables instead of <a class="reference internal" href="threading#threading.local" title="threading.local"><code>threading.local()</code></a> to prevent their state from bleeding to other code unexpectedly, when used in concurrent code.</p> <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> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.</span></p> </div> <section id="context-variables"> <h2>Context Variables</h2> <dl class="py class"> <dt class="sig sig-object py" id="contextvars.ContextVar">
+<code>class contextvars.ContextVar(name[, *, default])</code> </dt> <dd>
+<p>This class is used to declare a new Context Variable, e.g.:</p> <pre data-language="python">var: ContextVar[int] = ContextVar('var', default=42)
+</pre> <p>The required <em>name</em> parameter is used for introspection and debug purposes.</p> <p>The optional keyword-only <em>default</em> parameter is returned by <a class="reference internal" href="#contextvars.ContextVar.get" title="contextvars.ContextVar.get"><code>ContextVar.get()</code></a> when no value for the variable is found in the current context.</p> <p><strong>Important:</strong> Context Variables should be created at the top module level and never in closures. <a class="reference internal" href="#contextvars.Context" title="contextvars.Context"><code>Context</code></a> objects hold strong references to context variables which prevents context variables from being properly garbage collected.</p> <dl class="py attribute"> <dt class="sig sig-object py" id="contextvars.ContextVar.name">
+<code>name</code> </dt> <dd>
+<p>The name of the variable. This is a read-only property.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.1.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="contextvars.ContextVar.get">
+<code>get([default])</code> </dt> <dd>
+<p>Return a value for the context variable for the current context.</p> <p>If there is no value for the variable in the current context, the method will:</p> <ul class="simple"> <li>return the value of the <em>default</em> argument of the method, if provided; or</li> <li>return the default value for the context variable, if it was created with one; or</li> <li>raise a <a class="reference internal" href="exceptions#LookupError" title="LookupError"><code>LookupError</code></a>.</li> </ul> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="contextvars.ContextVar.set">
+<code>set(value)</code> </dt> <dd>
+<p>Call to set a new value for the context variable in the current context.</p> <p>The required <em>value</em> argument is the new value for the context variable.</p> <p>Returns a <a class="reference internal" href="#contextvars.Token" title="contextvars.Token"><code>Token</code></a> object that can be used to restore the variable to its previous value via the <a class="reference internal" href="#contextvars.ContextVar.reset" title="contextvars.ContextVar.reset"><code>ContextVar.reset()</code></a> method.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="contextvars.ContextVar.reset">
+<code>reset(token)</code> </dt> <dd>
+<p>Reset the context variable to the value it had before the <a class="reference internal" href="#contextvars.ContextVar.set" title="contextvars.ContextVar.set"><code>ContextVar.set()</code></a> that created the <em>token</em> was used.</p> <p>For example:</p> <pre data-language="python">var = ContextVar('var')
+
+token = var.set('new value')
+# code that uses 'var'; var.get() returns 'new value'.
+var.reset(token)
+
+# After the reset call the var has no value again, so
+# var.get() would raise a LookupError.
+</pre> </dd>
+</dl> </dd>
+</dl> <dl class="py class"> <dt class="sig sig-object py" id="contextvars.Token">
+<code>class contextvars.Token</code> </dt> <dd>
+<p><em>Token</em> objects are returned by the <a class="reference internal" href="#contextvars.ContextVar.set" title="contextvars.ContextVar.set"><code>ContextVar.set()</code></a> method. They can be passed to the <a class="reference internal" href="#contextvars.ContextVar.reset" title="contextvars.ContextVar.reset"><code>ContextVar.reset()</code></a> method to revert the value of the variable to what it was before the corresponding <em>set</em>.</p> <dl class="py attribute"> <dt class="sig sig-object py" id="contextvars.Token.var">
+<code>var</code> </dt> <dd>
+<p>A read-only property. Points to the <a class="reference internal" href="#contextvars.ContextVar" title="contextvars.ContextVar"><code>ContextVar</code></a> object that created the token.</p> </dd>
+</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="contextvars.Token.old_value">
+<code>old_value</code> </dt> <dd>
+<p>A read-only property. Set to the value the variable had before the <a class="reference internal" href="#contextvars.ContextVar.set" title="contextvars.ContextVar.set"><code>ContextVar.set()</code></a> method call that created the token. It points to <a class="reference internal" href="#contextvars.Token.MISSING" title="contextvars.Token.MISSING"><code>Token.MISSING</code></a> if the variable was not set before the call.</p> </dd>
+</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="contextvars.Token.MISSING">
+<code>MISSING</code> </dt> <dd>
+<p>A marker object used by <a class="reference internal" href="#contextvars.Token.old_value" title="contextvars.Token.old_value"><code>Token.old_value</code></a>.</p> </dd>
+</dl> </dd>
+</dl> </section> <section id="manual-context-management"> <h2>Manual Context Management</h2> <dl class="py function"> <dt class="sig sig-object py" id="contextvars.copy_context">
+<code>contextvars.copy_context()</code> </dt> <dd>
+<p>Returns a copy of the current <a class="reference internal" href="#contextvars.Context" title="contextvars.Context"><code>Context</code></a> object.</p> <p>The following snippet gets a copy of the current context and prints all variables and their values that are set in it:</p> <pre data-language="python">ctx: Context = copy_context()
+print(list(ctx.items()))
+</pre> <p>The function has an O(1) complexity, i.e. works equally fast for contexts with a few context variables and for contexts that have a lot of them.</p> </dd>
+</dl> <dl class="py class"> <dt class="sig sig-object py" id="contextvars.Context">
+<code>class contextvars.Context</code> </dt> <dd>
+<p>A mapping of <a class="reference internal" href="#contextvars.ContextVar" title="contextvars.ContextVar"><code>ContextVars</code></a> to their values.</p> <p><code>Context()</code> creates an empty context with no values in it. To get a copy of the current context use the <a class="reference internal" href="#contextvars.copy_context" title="contextvars.copy_context"><code>copy_context()</code></a> function.</p> <p>Every thread will have a different top-level <a class="reference internal" href="#contextvars.Context" title="contextvars.Context"><code>Context</code></a> object. This means that a <a class="reference internal" href="#contextvars.ContextVar" title="contextvars.ContextVar"><code>ContextVar</code></a> object behaves in a similar fashion to <a class="reference internal" href="threading#threading.local" title="threading.local"><code>threading.local()</code></a> when values are assigned in different threads.</p> <p>Context implements the <a class="reference internal" href="collections.abc#collections.abc.Mapping" title="collections.abc.Mapping"><code>collections.abc.Mapping</code></a> interface.</p> <dl class="py method"> <dt class="sig sig-object py" id="contextvars.Context.run">
+<code>run(callable, *args, **kwargs)</code> </dt> <dd>
+<p>Execute <code>callable(*args, **kwargs)</code> code in the context object the <em>run</em> method is called on. Return the result of the execution or propagate an exception if one occurred.</p> <p>Any changes to any context variables that <em>callable</em> makes will be contained in the context object:</p> <pre data-language="python">var = ContextVar('var')
+var.set('spam')
+
+def main():
+ # 'var' was set to 'spam' before
+ # calling 'copy_context()' and 'ctx.run(main)', so:
+ # var.get() == ctx[var] == 'spam'
+
+ var.set('ham')
+
+ # Now, after setting 'var' to 'ham':
+ # var.get() == ctx[var] == 'ham'
+
+ctx = copy_context()
+
+# Any changes that the 'main' function makes to 'var'
+# will be contained in 'ctx'.
+ctx.run(main)
+
+# The 'main()' function was run in the 'ctx' context,
+# so changes to 'var' are contained in it:
+# ctx[var] == 'ham'
+
+# However, outside of 'ctx', 'var' is still set to 'spam':
+# var.get() == 'spam'
+</pre> <p>The method raises a <a class="reference internal" href="exceptions#RuntimeError" title="RuntimeError"><code>RuntimeError</code></a> when called on the same context object from more than one OS thread, or when called recursively.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="contextvars.Context.copy">
+<code>copy()</code> </dt> <dd>
+<p>Return a shallow copy of the context object.</p> </dd>
+</dl> <dl class="describe"> <dt class="sig sig-object"> <span class="sig-name descname">var in context</span>
+</dt> <dd>
+<p>Return <code>True</code> if the <em>context</em> has a value for <em>var</em> set; return <code>False</code> otherwise.</p> </dd>
+</dl> <dl class="describe"> <dt class="sig sig-object"> <span class="sig-name descname">context[var]</span>
+</dt> <dd>
+<p>Return the value of the <em>var</em> <a class="reference internal" href="#contextvars.ContextVar" title="contextvars.ContextVar"><code>ContextVar</code></a> variable. If the variable is not set in the context object, a <a class="reference internal" href="exceptions#KeyError" title="KeyError"><code>KeyError</code></a> is raised.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="contextvars.Context.get">
+<code>get(var[, default])</code> </dt> <dd>
+<p>Return the value for <em>var</em> if <em>var</em> has the value in the context object. Return <em>default</em> otherwise. If <em>default</em> is not given, return <code>None</code>.</p> </dd>
+</dl> <dl class="describe"> <dt class="sig sig-object"> <span class="sig-name descname">iter(context)</span>
+</dt> <dd>
+<p>Return an iterator over the variables stored in the context object.</p> </dd>
+</dl> <dl class="describe"> <dt class="sig sig-object"> <span class="sig-name descname">len(proxy)</span>
+</dt> <dd>
+<p>Return the number of variables set in the context object.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="contextvars.Context.keys">
+<code>keys()</code> </dt> <dd>
+<p>Return a list of all variables in the context object.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="contextvars.Context.values">
+<code>values()</code> </dt> <dd>
+<p>Return a list of all variables’ values in the context object.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="contextvars.Context.items">
+<code>items()</code> </dt> <dd>
+<p>Return a list of 2-tuples containing all variables and their values in the context object.</p> </dd>
+</dl> </dd>
+</dl> </section> <section id="asyncio-support"> <h2>asyncio support</h2> <p>Context variables are natively supported in <a class="reference internal" href="asyncio#module-asyncio" title="asyncio: Asynchronous I/O."><code>asyncio</code></a> and are ready to be used without any extra configuration. For example, here is a simple echo server, that uses a context variable to make the address of a remote client available in the Task that handles that client:</p> <pre data-language="python">import asyncio
+import contextvars
+
+client_addr_var = contextvars.ContextVar('client_addr')
+
+def render_goodbye():
+ # The address of the currently handled client can be accessed
+ # without passing it explicitly to this function.
+
+ client_addr = client_addr_var.get()
+ return f'Good bye, client @ {client_addr}\n'.encode()
+
+async def handle_request(reader, writer):
+ addr = writer.transport.get_extra_info('socket').getpeername()
+ client_addr_var.set(addr)
+
+ # In any code that we call is now possible to get
+ # client's address by calling 'client_addr_var.get()'.
+
+ while True:
+ line = await reader.readline()
+ print(line)
+ if not line.strip():
+ break
+ writer.write(line)
+
+ writer.write(render_goodbye())
+ writer.close()
+
+async def main():
+ srv = await asyncio.start_server(
+ handle_request, '127.0.0.1', 8081)
+
+ async with srv:
+ await srv.serve_forever()
+
+asyncio.run(main())
+
+# To test it you can use telnet:
+# telnet 127.0.0.1 8081
+</pre> </section> <div class="_attribution">
+ <p class="_attribution-p">
+ &copy; 2001&ndash;2023 Python Software Foundation<br>Licensed under the PSF License.<br>
+ <a href="https://docs.python.org/3.12/library/contextvars.html" class="_attribution-link">https://docs.python.org/3.12/library/contextvars.html</a>
+ </p>
+</div>