Python Glossary Русский

Python 3.7+contextvarsterm

contextvars.Context

context variables

A mapping from ContextVar to value; its run() method executes a function inside that context.

Syntax

ctx = contextvars.Context(); ctx.run(callable, *args, **kwargs)

Context() creates an empty context — variables in it see only their defaults, not the current values; copy_context() gives a snapshot of the current one. The mapping cannot be changed directly: ctx[var] = x does not work, values change only via set() inside run(). The same context cannot be entered twice at once — a nested ctx.run() on the same ctx raises RuntimeError.

Examples

import contextvars
lang = contextvars.ContextVar('lang', default='ru')
lang.set('en')
print(contextvars.Context().run(lang.get))  # → ru — пустой контекст
print(contextvars.copy_context().run(lang.get))  # → en
ctx = contextvars.Context()
try:
    ctx.run(ctx.run, lang.get)
except RuntimeError:
    print('уже внутри этого контекста')  # → уже внутри этого контекста

See also

Open in the full glossarydocs.python.orgReport an inaccuracy