Python Context Variables

Context variable can have different values depending on its context. Unlike Thread-Local Storage where each execution thread may have a different value for a variable, a context variable may be several contexts in one execution thread. This is useful in keeping track of variables in concurrent asynchronous tasks.

The ContextVar class is used to declare and work with Context Variables.

import contextvars
name = contextvars.ContextVar("name", default = 'Hello')

The optional default parameter is returned by ContextVar.get() when no value for the variable is found in the current context.

name: The name of the variable. This is a read-only property.

Following methods are defined in ContextVar class

get()Return a value for the context variable for the current context. If there is no value for the variable in the current context, the method will −
  • return the value of the default argument of the method, if provided − or

  • return the default value for the context variable, if it was created with one − or

  • raise a LookupError.

set()Call to set a new value for the context variable in the current context.
reset()Reset the context variable to the value it had before the ContextVar.set() that created the token was used.

Context class in context vars module is a mapping of Context Vars to their values.

Context(): creates an empty context with no values in it.

To get a copy of the current context use the copy_context() function.

The run(callable, *args, **kwargs) method executes callable(*args, **kwargs) code in the context object the run method is called on and returns the result of the execution. Any changes to any context variables that callable makes, will be contained in the context object. The method raises a RuntimeError when called on the same context object from more than one OS thread, or when called recursively.

copy()returns a shallow copy of the context object.
context[var]returns the value of the var ContextVar variable. If the variable is not set in the context object, a Key Error is raised.
get()returns the value for context var if it has the value in the context object. otherwise, it returns to default. If default is not given, return None.
iter()returns an iterator over the variables stored in the context object.
len()returns the number of variables set in the context object.
keys()returns a list of all variables in the context object.
values()returns a list of all variables’ values in the context object.
    items()returns a list of 2-tuples containing all variables and their values in the context object.