Debian Codegraph @

Doc/library/contextvars.rst

raw
1 :mod:`!contextvars` --- Context Variables
2 =========================================
3
4 .. module:: contextvars
5 :synopsis: Context Variables
6
7 .. sectionauthor:: Yury Selivanov <[email protected]>
8
9 --------------
10
11 This module provides APIs to manage, store, and access context-local
12 state. The :class:`~contextvars.ContextVar` class is used to declare
13 and work with *Context Variables*. The :func:`~contextvars.copy_context`
14 function and the :class:`~contextvars.Context` class should be used to
15 manage the current context in asynchronous frameworks.
16
17 Context managers that have state should use Context Variables
18 instead of :func:`threading.local` to prevent their state from
19 bleeding to other code unexpectedly, when used in concurrent code.
20
21 See also :pep:`567` for additional details.
22
23 .. versionadded:: 3.7
24
25
26 Context Variables
27 -----------------
28
29 .. class:: ContextVar(name, [*, default])
30
31 This class is used to declare a new Context Variable, e.g.::
32
33 var: ContextVar[int] = ContextVar('var', default=42)
34
35 The required *name* parameter is used for introspection and debug
36 purposes.
37
38 The optional keyword-only *default* parameter is returned by
39 :meth:`ContextVar.get` when no value for the variable is found
40 in the current context.
41
42 **Important:** Context Variables should be created at the top module
43 level and never in closures. :class:`Context` objects hold strong
44 references to context variables which prevents context variables
45 from being properly garbage collected.
46
47 .. attribute:: ContextVar.name
48
49 The name of the variable. This is a read-only property.
50
51 .. versionadded:: 3.7.1
52
53 .. method:: get([default])
54
55 Return a value for the context variable for the current context.
56
57 If there is no value for the variable in the current context,
58 the method will:
59
60 * return the value of the *default* argument of the method,
61 if provided; or
62
63 * return the default value for the context variable,
64 if it was created with one; or
65
66 * raise a :exc:`LookupError`.
67
68 .. method:: set(value)
69
70 Call to set a new value for the context variable in the current
71 context.
72
73 The required *value* argument is the new value for the context
74 variable.
75
76 Returns a :class:`~contextvars.Token` object that can be used
77 to restore the variable to its previous value via the
78 :meth:`ContextVar.reset` method.
79
80 .. method:: reset(token)
81
82 Reset the context variable to the value it had before the
83 :meth:`ContextVar.set` that created the *token* was used.
84
85 For example::
86
87 var = ContextVar('var')
88
89 token = var.set('new value')
90 # code that uses 'var'; var.get() returns 'new value'.
91 var.reset(token)
92
93 # After the reset call the var has no value again, so
94 # var.get() would raise a LookupError.
95
96 The same *token* cannot be used twice.
97
98
99 .. class:: Token
100
101 *Token* objects are returned by the :meth:`ContextVar.set` method.
102 They can be passed to the :meth:`ContextVar.reset` method to revert
103 the value of the variable to what it was before the corresponding
104 *set*. A single token cannot reset a context variable more than once.
105
106 .. attribute:: Token.var
107
108 A read-only property. Points to the :class:`ContextVar` object
109 that created the token.
110
111 .. attribute:: Token.old_value
112
113 A read-only property. Set to the value the variable had before
114 the :meth:`ContextVar.set` method call that created the token.
115 It points to :attr:`Token.MISSING` if the variable was not set
116 before the call.
117
118 .. attribute:: Token.MISSING
119
120 A marker object used by :attr:`Token.old_value`.
121
122
123 Manual Context Management
124 -------------------------
125
126 .. function:: copy_context()
127
128 Returns a copy of the current :class:`~contextvars.Context` object.
129
130 The following snippet gets a copy of the current context and prints
131 all variables and their values that are set in it::
132
133 ctx: Context = copy_context()
134 print(list(ctx.items()))
135
136 The function has an *O*\ (1) complexity, i.e. works equally fast for
137 contexts with a few context variables and for contexts that have
138 a lot of them.
139
140
141 .. class:: Context()
142
143 A mapping of :class:`ContextVars <ContextVar>` to their values.
144
145 ``Context()`` creates an empty context with no values in it.
146 To get a copy of the current context use the
147 :func:`~contextvars.copy_context` function.
148
149 Each thread has its own effective stack of :class:`!Context` objects. The
150 :term:`current context` is the :class:`!Context` object at the top of the
151 current thread's stack. All :class:`!Context` objects in the stacks are
152 considered to be *entered*.
153
154 *Entering* a context, which can be done by calling its :meth:`~Context.run`
155 method, makes the context the current context by pushing it onto the top of
156 the current thread's context stack.
157
158 *Exiting* from the current context, which can be done by returning from the
159 callback passed to the :meth:`~Context.run` method, restores the current
160 context to what it was before the context was entered by popping the context
161 off the top of the context stack.
162
163 Since each thread has its own context stack, :class:`ContextVar` objects
164 behave in a similar fashion to :func:`threading.local` when values are
165 assigned in different threads.
166
167 Attempting to enter an already entered context, including contexts entered in
168 other threads, raises a :exc:`RuntimeError`.
169
170 After exiting a context, it can later be re-entered (from any thread).
171
172 Any changes to :class:`ContextVar` values via the :meth:`ContextVar.set`
173 method are recorded in the current context. The :meth:`ContextVar.get`
174 method returns the value associated with the current context. Exiting a
175 context effectively reverts any changes made to context variables while the
176 context was entered (if needed, the values can be restored by re-entering the
177 context).
178
179 Context implements the :class:`collections.abc.Mapping` interface.
180
181 .. method:: run(callable, *args, **kwargs)
182
183 Enters the Context, executes ``callable(*args, **kwargs)``, then exits the
184 Context. Returns *callable*'s return value, or propagates an exception if
185 one occurred.
186
187 Example:
188
189 .. testcode::
190
191 import contextvars
192
193 var = contextvars.ContextVar('var')
194 var.set('spam')
195 print(var.get()) # 'spam'
196
197 ctx = contextvars.copy_context()
198
199 def main():
200 # 'var' was set to 'spam' before
201 # calling 'copy_context()' and 'ctx.run(main)', so:
202 print(var.get()) # 'spam'
203 print(ctx[var]) # 'spam'
204
205 var.set('ham')
206
207 # Now, after setting 'var' to 'ham':
208 print(var.get()) # 'ham'
209 print(ctx[var]) # 'ham'
210
211 # Any changes that the 'main' function makes to 'var'
212 # will be contained in 'ctx'.
213 ctx.run(main)
214
215 # The 'main()' function was run in the 'ctx' context,
216 # so changes to 'var' are contained in it:
217 print(ctx[var]) # 'ham'
218
219 # However, outside of 'ctx', 'var' is still set to 'spam':
220 print(var.get()) # 'spam'
221
222 .. testoutput::
223 :hide:
224
225 spam
226 spam
227 spam
228 ham
229 ham
230 ham
231 spam
232
233 .. method:: copy()
234
235 Return a shallow copy of the context object.
236
237 .. describe:: var in context
238
239 Return ``True`` if the *context* has a value for *var* set;
240 return ``False`` otherwise.
241
242 .. describe:: context[var]
243
244 Return the value of the *var* :class:`ContextVar` variable.
245 If the variable is not set in the context object, a
246 :exc:`KeyError` is raised.
247
248 .. method:: get(var, [default])
249
250 Return the value for *var* if *var* has the value in the context
251 object. Return *default* otherwise. If *default* is not given,
252 return ``None``.
253
254 .. describe:: iter(context)
255
256 Return an iterator over the variables stored in the context
257 object.
258
259 .. describe:: len(proxy)
260
261 Return the number of variables set in the context object.
262
263 .. method:: keys()
264
265 Return a list of all variables in the context object.
266
267 .. method:: values()
268
269 Return a list of all variables' values in the context object.
270
271
272 .. method:: items()
273
274 Return a list of 2-tuples containing all variables and their
275 values in the context object.
276
277
278 asyncio support
279 ---------------
280
281 Context variables are natively supported in :mod:`asyncio` and are
282 ready to be used without any extra configuration. For example, here
283 is a simple echo server, that uses a context variable to make the
284 address of a remote client available in the Task that handles that
285 client::
286
287 import asyncio
288 import contextvars
289
290 client_addr_var = contextvars.ContextVar('client_addr')
291
292 def render_goodbye():
293 # The address of the currently handled client can be accessed
294 # without passing it explicitly to this function.
295
296 client_addr = client_addr_var.get()
297 return f'Good bye, client @ {client_addr}\r\n'.encode()
298
299 async def handle_request(reader, writer):
300 addr = writer.transport.get_extra_info('socket').getpeername()
301 client_addr_var.set(addr)
302
303 # In any code that we call is now possible to get
304 # client's address by calling 'client_addr_var.get()'.
305
306 while True:
307 line = await reader.readline()
308 print(line)
309 if not line.strip():
310 break
311
312 writer.write(b'HTTP/1.1 200 OK\r\n') # status line
313 writer.write(b'\r\n') # headers
314 writer.write(render_goodbye()) # body
315 writer.close()
316
317 async def main():
318 srv = await asyncio.start_server(
319 handle_request, '127.0.0.1', 8081)
320
321 async with srv:
322 await srv.serve_forever()
323
324 asyncio.run(main())
325
326 # To test it you can use telnet or curl:
327 # telnet 127.0.0.1 8081
328 # curl 127.0.0.1:8081