Context variables are variables that can have different values depending on their context. They are similar to Thread-Local Storage in which each execution thread may have a different value for a variable. However, with context variables, there may be several contexts in one execution thread. The main use case for context variables is keeping track of variables in concurrent asynchronous tasks. -- https://realpython.com/python37-new-features/#context-variables
"""Example copied verbatim from Real Python."""
import contextvars
name = contextvars.ContextVar("name")
contexts = list()
def greet():
print(f"Hello {name.get()}")
# Construct contexts and set the context variable name
for first_name in ["Steve", "Dina", "Harry"]:
ctx = contextvars.copy_context()
ctx.run(name.set, first_name)
contexts.append(ctx)
# Run greet function inside each context
for ctx in reversed(contexts):
ctx.run(greet)
Unique context vars are created per object and not per name. If some-other module creates context var with same name inside your context, it'd mess with your lookup.
https://gist.github.com/Integralist/4e2f323f29ceb624f7fd540687d8e74f#file-2-python-context-py-L62-L78