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