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 contextvars
cvar = contextvars.ContextVar( "cvar" ,
default = "variable" )
print ( "value of context variable cvar: \n" ,
cvar.get())
token = cvar. set ( "changed" )
print ( "\nvalue after calling set method: \n" ,
cvar.get())
print ( "\nType of object instance returned by set method: \n" ,
type (token))
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
cvar = contextvars.ContextVar( "cvar" , default = "variable" )
token = cvar. set ( "changed" )
print ( "ContextVar object though which token was generated: " )
print (token.var)
print ( "\nAfter calling token.old_value : " )
print (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 c
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
7 min read
Access environment variable values in Python
An environment variable is a variable that is created by the Operating System. Environment variables are created in the form of Key-Value pairs. To Access environment variables in Python's we can use the OS module which provides a property called environ that contains environment variables in key-va
3 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
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
Variable Shadowing in Python
In this article, we will understand the concept of variable shadowing in a Python programming language. To understand this concept, we need to be well versed with the scope of a lifetime of variables in python. Local variables:When we define a function, we can create variables that are scoped only t
3 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
__name__ (A Special variable) in Python
Since there is no main() function in Python, when the command to run a python program is given to the interpreter, the code that is at level 0 indentation is to be executed. However, before doing that, it will define a few special variables. __name__ is one such special variable. If the source file
2 min read
Python range() function
The Python range() function returns a sequence of numbers, in a given range. The most common use of it is to iterate sequences on a sequence of numbers using Python loops. Example In the given example, we are printing the number from 0 to 4. [GFGTABS] Python for i in range(5): print(i, end="
7 min read
How to write Comments in Python3?
Comments are text notes added to the program to provide explanatory information about the source code. They are used in a programming language to document the program and remind programmers of what tricky things they just did with the code and also help the later generation for understanding and mai
4 min read