Python contextvars Module
Example
Create and use a ContextVar:
import contextvars
user = contextvars.ContextVar("user", default="Emil")
print(user.get())
token = user.set("Tobias")
print(user.get())
Try it Yourself »
Definition and Usage
The contextvars module provides context-local state, useful for asynchronous code.
Use it to store and retrieve values that are specific to a particular execution context.
Members
| Member | Description |
|---|---|
| Context | Container for context variables. |
| Context.copy() | Return a shallow copy of this Context. |
| Context.run() | Run a callable within this Context. |
| ContextVar | Context variable class. |
| ContextVar.get() | Get the current value (or default) of the variable. |
| ContextVar.reset() | Reset the variable to the value before the last set() using a Token. |
| ContextVar.set() | Set the variable to a new value and return a Token for later reset. |
| copy_context() | Return a shallow copy of the current context. |
| Token | Opaque object returned by ContextVar.set() for later reset. |