On this page
contextvars.ContextVar
Prev: contextvars.Context | Up: contextvars | Next: contextvars.copy_context
Rel: contextvars.Context, contextvars.copy_context, contextvars.Token
Ref: docs.python.org — contextvars.ContextVar
Tags: #public #python3 #stdlib #contextvars
Import
import contextvars
from contextvars import ContextVar
Signature & Overview
contextvars.ContextVar(...)
contextvars.ContextVar class.
Methods & Attributes
ContextVar.get(...)— Return a value for the context variable for the current context.ContextVar.reset(self, token, /)— Reset the context variable.ContextVar.set(self, value, /)— Call to set a new value for the context variable in the current context.
Usage
import contextvars
req_id: contextvars.ContextVar[str] = contextvars.ContextVar("req_id", default="-")
tok = req_id.set("req-42")
try:
assert req_id.get() == "req-42"
finally:
req_id.reset(tok)
assert req_id.get() == "-"
Gotchas
- Async-safe replacement for
threading.local(): Always reset viavar.reset(token)in afinally:block. - Avoid mutable defaults (
default=[]): Usedefault=Noneinstead, because a single default list would be shared across all contexts.
REPL Inspect
from contextvars import ContextVar
help(ContextVar)
Linked from
Related notes
- tuts/python3/stdlib_module/contextvars/Context 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