Context Variables in Python
Last Updated :
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.
Example :
Python3
# import module
import contextvars
# declaring the variable
# to it's default value
cvar = contextvars.ContextVar("cvar",
default = "variable")
print("value of context variable cvar: \n",
cvar.get())
# calling set method
token = cvar.set("changed")
print("\nvalue after calling set method: \n",
cvar.get())
# checking the type of token instance
print("\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 class in contextvars :
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.
Example :
Python3
import contextvars
# declaring the variable
cvar = contextvars.ContextVar("cvar", default = "variable")
# calling set function to get a token object
token = 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_value
token = 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
Context class in contextvars :
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.
Similar Reads
Environment Variables in Python
Environment variables are key-value pairs that live in our system's environment. Python reads some of these variables at startup to determine how to behave, for example, where to look for modules or whether to enter interactive mode.If thereâs ever a conflict between an environment variable and a co
3 min read
Python Variables
In Python, variables are used to store data that can be referenced and manipulated during program execution. A variable is essentially a name that is assigned to a value. Unlike many other programming languages, Python variables do not require explicit declaration of type. The type of the variable i
6 min read
How to use Variables in Python3?
Variable is a name for a location in memory. It can be used to hold a value and reference that stored value within a computer program. the interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to the variables, you can store
3 min read
Python Scope of Variables
In Python, variables are the containers for storing data values. Unlike other languages like C/C++/JAVA, Python is not âstatically typedâ. We do not need to declare variables before using them or declare their type. A variable is created the moment we first assign a value to it. Python Scope variabl
5 min read
Viewing all defined variables in Python
In this article, we are going to discuss how to view all defined variables in Python. Viewing all defined variables plays a major role while debugging the code. Method 1: Using dir() function dir() is a built-in function to store all the variables inside a program along with the built-in variable fu
5 min read
Conftest in pytest
The testing framework in Python that is used to write various types of software tests, including unit tests, integration tests, etc is called Pytest. The Pytest gives the user the ability to use the common input in various Python files, this is possible using Conftest. The conftest.py is the Python
2 min read
Python dictionary values()
values() method in Python is used to obtain a view object that contains all the values in a dictionary. This view object is dynamic, meaning it updates automatically if the dictionary is modified. If we use the type() method on the return value, we get "dict_values object". It must be cast to obtain
2 min read
How To Print A Variable's Name In Python
In Python, printing a variable's name can be a useful debugging technique or a way to enhance code readability. While the language itself does not provide a built-in method to directly obtain a variable's name, there are several creative ways to achieve this. In this article, we'll explore five simp
3 min read
Context Manager in Python
Managing Resources: In any programming language, the usage of resources like file operations or database connections is very common. But these resources are limited in supply. Therefore, the main problem lies in making sure to release these resources after usage. If they are not released then it wil
5 min read
__exit__ in Python
Context manager is used for managing resources used by the program. After completion of usage, we have to release memory and terminate connections between files. If they are not released then it will lead to resource leakage and may cause the system to either slow down or crash. Even if we do not re
3 min read