Context Variables in Python

17 Aug, 2020
Context variable objects in Python is an interesting type of variable which returns the value of variable according to the context. It may have multiple values according to context in single thread or execution. The ContextVar class present in contextvars module, which is used to declare and work with context variables in python. 
Note: This is supported in python version >= 3.7.
Following is the simple syntax to declare a complex variable :
Syntax: contextvars.ContextVar(name, default)
Parameter:
name: Name of the variable which can be used for reference or debug process.
default: Returns the value of this variable in particular context. If there is no value in the context then it will return the default value.
Return: contextvars class object.
Note: Context variables should always be created at the top of program, never in the functions or middle blocks of program. 
Following are the methods defined in ContextVar class :
get(): Returns the value of context variable in the particular context, if it does not contain any then It will return the default value provided if provided, else raise a lookup error.set(value): This method is called to set a new value provided as parameter to the context variable in the particular context it is called in.reset(token): This method resets the value of context variable to that of before ContextVar.set() was called in reference to token returned by set() method.
get(): Returns the value of context variable in the particular context, if it does not contain any then It will return the default value provided if provided, else raise a lookup error.
set(value): This method is called to set a new value provided as parameter to the context variable in the particular context it is called in.
reset(token): This method resets the value of context variable to that of before ContextVar.set() was called in reference to token returned by set() method.
Example :
Python3
# import moduleimport contextvars  # declaring the variable # to it's default valuecvar = contextvars.ContextVar("cvar",                              default = "variable")  print("value of context variable cvar: \n",      cvar.get())  # calling set methodtoken = cvar.set("changed")  print("\nvalue after calling set method: \n",      cvar.get())  # checking the type of token instanceprint("\nType of object instance returned by set method: \n",      type(token))  # calling the reset method.cvar.reset(token)  print("\nvalue after calling reset method: \n",      cvar.get())
Output :
value of context variable cvar: 
variable

value after calling set method: 
changed

Type of object instance returned by set method: 
<class 'Token'>

value after calling reset method: 
variable

Token objects are returned by ContextVar.set() method and can be reused as parameter in ContextVar.reset(token) method to reset its value to previous token context variable as described above. 
Following are the properties that can be used with token object :
Token.var: It returns the ContextVar object that was used to create this token returned by CotextVar.set() method. This has read only property, this is not callable.Token.old_value: Set to the value that variable had before calling of ContextVar.set() method because of which the token was generated. It is not callable, it has read only property. It points to Token.MISSING if the variable was not set before the call.Token.MISSING: Used as a marker by Token.old_value.
Token.var: It returns the ContextVar object that was used to create this token returned by CotextVar.set() method. This has read only property, this is not callable.
Token.old_value: Set to the value that variable had before calling of ContextVar.set() method because of which the token was generated. It is not callable, it has read only property. It points to Token.MISSING if the variable was not set before the call.
Token.MISSING: Used as a marker by Token.old_value.
Example :
Python3
import contextvars  # declaring the variablecvar = contextvars.ContextVar("cvar", default = "variable")  # calling set function to get a token objecttoken = cvar.set("changed")  # token.var returns the ContextVar# object through which token is generated.print("ContextVar object though which token was generated: ")print(token.var)  # As only one time set is called# it should return token.MISSING.print("\nAfter calling token.old_value : ")print(token.old_value)  # Recalling set method again to# test other side of token.old_valuetoken = cvar.set("changed_2")print("\nPrinting the value set before set method called last : ")print(token.old_value)  print("\nThe current value of context variable is : ")print(cvar.get())
Output :
ContextVar object though which token was generated:
<ContextVar name='cvar' default='variable' at 7f82d7c07048>

After calling token.old_value : 
<object object at 0x7f8305801720>

Printing the value set before set method called last : 
changed 

The current value of context variable is : 
changed_2

This context class in the contextvars module is the mapping of context variables to their values. This can also be called as manual context manager. 
Following are some methods of this class :
context(): creates an empty context with no values in it.
get(): returns the value of current variable if assigned, otherwise returns the default value if given, otherwise returns None.
keys(): returns the list of all variables in the contextvars object.
items(): returns the list of tuples with two elements in each tuple, first the name of variable and second its value for all the variables present in contextvars object.
len(): returns the number of variables present in contextvars object.
values(): returns a list of values of all the variables present in contextvars object.
iter(): returns an iterator object which iterates over all the variables present in our contextvars object.
copy_context(): returns a shallow copy of current contextvars object.
run(callable, *args, **kwargs): Executes the function callable(*args, **kwargs) in the context to which run method is called and it returns the result of the program in callable function.
python-basics
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate over a list in Python
Rotate axis tick labels in Seaborn and Matplotlib
Enumerate() in Python
Deque in Python
Stack in Python
Python Dictionary
sum() function in Python
Print lists in Python (5 Different Ways)
Different ways to create Pandas Dataframe
Queue in Python