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