Python 3.7+contextvarsfunction
contextvars.copy_context()
context variables
Returns a snapshot of the current context — a Context object holding every context variable's value at that moment.
Syntax
ctx = contextvars.copy_context()
It is a copy, not a reference: changes made after copying do not reach the snapshot, and set() inside ctx.run() stays in the snapshot and never leaks out. Copying is cheap (an immutable mapping), which is how asyncio gives each task its own context. You pass the snapshot to things like loop.call_soon(..., context=ctx) or asyncio.create_task(..., context=ctx).
Examples
import contextvars
mode = contextvars.ContextVar('mode', default='-')
mode.set('a')
ctx = contextvars.copy_context()
mode.set('b')
print(ctx[mode], mode.get()) # → a b
def change():
mode.set('inside')
return mode.get()
print(ctx.run(change), mode.get(), ctx[mode]) # → inside b inside
See also
Open in the full glossarydocs.python.orgReport an inaccuracy