Python 3.7+contextvarsterm
contextvars
module
Context variables: a value of its own for each asynchronous task and each context.
Syntax
import contextvars
Use it when asynchronous code needs something like a global variable — a request id, the current user — that does not leak between tasks. threading.local does not work for this: all coroutines in one thread share its value. Change the value with set and roll it back with reset using the returned token; each asyncio task gets a copy of the context.
Examples
import contextvars
user = contextvars.ContextVar('user', default='гость')
token = user.set('Аня')
print(user.get()) # → Аня
user.reset(token)
print(user.get()) # → гость
See also
Open in the full glossarydocs.python.orgReport an inaccuracy