Python

Python Context Manager

Managing Resources

The use of resources such as file manipulations or database access is quite prevalent in all computer languages. However, there is a finite number of these resources. We have to ensure that restoring such resources after use would be the key obstacle. When they’re not given, resource leakage will occur, and it slows down or even damages the computer. The ability for users to build up and break down reallocating resources will be massively valuable. Python context managers that make it easier to handle resources effectively could be used to accomplish this.

Context Manager for Resource Management

It’ll become difficult to close a file immediately when a piece of code throws an error or has a complicated mechanism, including many returned pathways. Try-except-finally is typically utilized in certain programming languages to assure that. Indeed file resource is terminated after using it, although there is an error. Context Managers, a module of Python, enable resource management simply. The term “with” will be utilized. This will create an object that manages context until it has been analyzed. Classes or processes with modifiers would be utilized to create context managers. Let’s discuss more context manager.

Example no 1

While utilizing classes to construct context managers, make sure that the class contains the functions like enter() and exit(). The cleanup activities are carried out via the exit() function, which will return nothing but the function enter() provides the resource that requires development. To analyze the framework of generating context managers with classes, let’s first develop a basic class named ContextManager, as seen here:

class ContextManager():

    def __init__(self1):
        print('init function will be called')
         
    def __enter__(self2):
        print('enter function will be called ')
        return self2
     
    def __exit__(self2, exc_type, exc_value, exc_traceback):
        print('exit function will be called')
 
with ContextManager() as manager:
    print('Here is the with statement')


At the beginning of the code, we create a class termed as ContextManager. Within this class, we define a function init(). Then we utilize the print() method to display the statement “init function will be called”. In the next line, another function, enter(), will be defined. This function contains “self2” as an argument. We will call the print() method to print the statement “enter function will be called”. Then the return statement is called.

Let’s define a new function named exit(). This function has four different arguments, which contain the value of self2, exc_type, exc_value, and exc_traceback. For this function, the print() statement is also being applied to show the line “exit function will be called”. Lastly, we will create an object manager of the ContextManager class. We employ a print() statement which shows the message “Here is the with the statement”.


A ContextManager instance is generated in this example. The attribute after the term “manager” is given this allocation. The following functions are carried out sequentially upon executing the aforementioned code:

  • init()
  • enter()
  • A declaration body that contains code within a “with” section.
  • exit(). The arguments of this function are being utilized to control errors.

Example no 2

Let’s use the preceding approach to build a class that aids in managing file resources. The FileManager class facilitates accessing, writing to or reading from, and terminating files.

class FileManager():

    def __init__(self1, filename, mode):
        self1.filename = filename
        self1.mode = mode
        self1.file = None
         
    def __enter__(self2):
        self2.file = open(self2.filename, self2.mode)
        return self2.file
     
    def __exit__(self2, exc_type, exc_value, exc_traceback):
        self2.file.close()

with FileManager('hello.txt', 'w') as f:
    f.write('Test')


 

print(f.closed)


First of all, we create a class known as “FileManager”. Now we define different functions related to this class. First, we define the function of init(). Within this function, we pass three various arguments. The first parameter is “self1”, the second parameter shows the name of the file “filename”, and the last parameter shows the “mode” of the file. We create an object termed a filename and set its value equal to the original name of the required file.

Then we create another object called “mode”, and here we specify the format of the defined file. We declare the last object named as “file,” and now the value of this object will be set as “None”. Let’s initialize another function enter(). We provide the value of “self2” as an argument for this function. Here we call the open() method to open the specified file. This function holds two parameters which include the name of the file which we want to open and the mode of opening the file. The mode parameter shows for which purpose we want to open the file. The mode of the file will be “write”, or “read”.

Then we utilize the return statement. In the next step, we want to exit that file. So we apply the exit() method. We will pass four arguments to this function. Then we utilize the FileManager() method. We load a file by using this function. Within this function, we specify the text which we want to write in the file. And also, we specify the mode of the file “w”. Now we apply the write() method. To terminate the code, we employ the print() method. Within this function, we utilize a close statement to just close the file.


By utilizing context manager, we will manage files. When the “with” block is implemented, the appropriate steps take place one after another:

  • Whenever the init() function is called, a FileManager instance is constructed, having hello.txt as the title of the file and “w” as the format of the fi• The hello.txt file is accessed in write format by the enter() function, which also returns a file class to the attribute f.
  • The file contains the content “Test.”
  • When the with section is terminated, the exit() function handles closing the file. Because the FileManager has indeed effectively managed the termination of the file, which would have normally been required to handle explicitly, when print(f.closed) is executed, the outcome will be True.

Conclusion

In this article, we have talked about the python context manager. We can assign and utilize the resources at the specific times that we choose due to context managers. The “with” expression is the most frequently used illustration of a context manager. Whenever we want to pair up two related events and implement a piece of code between them, we utilize context managers. We execute an example in which we demonstrate the creation of a context manager. We manipulate files by the use of a context manager and with commands.

About the author

Kalsoom Bibi

Hello, I am a freelance writer and usually write for Linux and other technology related content