1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
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">
© 2001–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>
|