On this page
contextvars.Context
Up: contextvars | Next: contextvars.ContextVar
Rel: contextvars.ContextVar, contextvars.copy_context, contextvars.Token
Ref: docs.python.org — contextvars.Context
Tags: #public #python3 #stdlib #contextvars
Import
import contextvars
from contextvars import Context
Signature & Overview
contextvars.Context(...)
contextvars.Context class.
Methods & Attributes
Context.copy(self, /)— Return a shallow copy of the context object.Context.get(self, key, default=None, /)— Return the value forkeyifkeyhas the value in the context object.Context.items(self, /)— Return all variables and their values in the context object.Context.keys(self, /)— Return a list of all variables in the context object.Context.run(...)—Context.runmethod/property.Context.values(self, /)— Return a list of all variables' values in the context object.
Usage
import contextvars
var = contextvars.ContextVar("user", default="anon")
ctx = contextvars.Context()
assert ctx.run(var.get) == "anon"
Gotchas
- Each
Context.run()isolates mutations: Changes insidectx.run(...)don't leak to the caller's context or otherasynciotasks.
REPL Inspect
from contextvars import Context
help(Context)
Linked from
Related notes
- tuts/python3/stdlib_module/contextvars/ContextVar Linked here; links to this page; shared tags: #contextvars, #stdlib
- tuts/python3/stdlib_module/contextvars/copy_context Linked here; links to this page; shared tags: #contextvars, #stdlib
- tuts/python3/stdlib_module/contextvars/Token Linked here; links to this page; shared tags: #contextvars, #stdlib
- tuts/python3/stdlib_module/contextvars Linked here; links to this page; shared tags: #stdlib
- tuts/c/stdlib shared tags: #stdlib
- tuts/c/stdlib/assert shared tags: #stdlib
- tuts/c/stdlib/assert/assert shared tags: #stdlib
- tuts/c/stdlib/assert/static_assert shared tags: #stdlib
- tuts/c/stdlib/ctype shared tags: #stdlib
- tuts/c/stdlib/ctype/isalpha shared tags: #stdlib