Updated April 15, 2023
Introduction to Python Context Manager
A context manager is resource management. Generally, in any other programming languages, the resource is managed using try-except-finally blocks when working with files, but it should be noted that the file resources must be closed after the usage else resources will not be released to other files, which may lead to resource leakage which will slow down your systems. Context managers will allow you to allocate and release the resources when it is needed. In Python, the easiest way for resource management can be done using context manager, and to perform file operations, it is done using the “with” keyword.
Working of Context Manager with Examples
As to what exactly is context manager and how it is used, we need to understand it. Context managers are the managers to manage resources. Say when a program wants to access the computer resources, it will first ask OS, and OS will provide it back to the program that requested that resource. E.g. Examples for resources are like files, network ports, etc. Let us consider how to open the file, read and close the file:
open_file =open('text.txt')
text = open_file.read()
……
open_file.close()
In the above simple example, we are reading the text.txt file with read() method and the contents are stored in the string variable text, and after some statements or work is done, we have to close the file using the close() method. But in such type of coding, we may forget to close the files most of the time and also there might occur some unexpected events (exceptions) which forcefully closes the file while it is executing, so to handle such a problem we use try… else blocks in any programming languages which will make sure that code in else part is always executed. But in Python, it can be done using the “with” keyword:
Example:
with open('Text.txt', 'w') as fl:
fl.write('Educba Training in Pune')
fl =open('Text.txt', 'r+')
contents = fl.read()
print(contents)
Output:
So in the above example “with” statement is used because it ensures that open file descriptors are closed automatically after the execution of the program. So in actual the above code internally looks like this:
fl = open('Text.txt', 'w' )
try:
fl.write('Educba Training')
finally:
fl.close()
fl =open('Text.txt', 'r+')
contents = fl.read()
print(contents)
Output:
Or it can also be written in simple code as below without any try and finally block:
fl = open('Text.txt', 'w' )
fl.write('Educba Training….')
fl.close()
fl =open('Text.txt', 'r+')
contents = fl.read()
print(contents)
Output:
But as discussed earlier, the above code without an ‘with’ statement will not guarantee you that the file is closed because there might be some exceptions while writing the contexts to the file. Therefore ‘with’ statements are used, which ensure allocation and releasing of resources properly.
Implementing a Context Manager as a Class
It has two methods _enter_() and _exit_() in the class. The _enter_() method is called when the execution of the program enters the context, and the _exit_() method is called when execution leaves the context again to release the resources. Let us take an example:
class demo_file():
def __init__(self):
print("This is initial method being called")
def __enter__(self):
print("The enter method is being called")
return self
def __exit__(self, exc_type, exc_value, exc_traceback):
print("The exit method is being called")
with demo_file() as context_manager:
print("This is the block where program is executed before closing the file")
Output:
In this above program, the demo_file object is created of the class demo_file and then assigned to a variable after the keyword in with statement fl. Firstly the __init__ method is executed where fl is initialized, and then the __enter__ method is executed where the file is opened with write mode, and then it returns the object by writing the content to the file. Then with statement will close the file, and then the __exit__ method is called, and it exits from the with the statement and the parameters used in __exit__method are used for handling exceptions.
Using the above now, we will manage files using context manager:
class file_manager():
def __init__(self, file_name, mode):
self.file_name = file_name
self. mode = mode
self.file = None
def __enter__(self):
self.file = open (self.file_name, self. mode)
return self.file
def __exit__(self, exc_type, exc_value, exc_traceback):
self.file.close()
with file_manager("Text.txt", 'w') as fl:
fl.write("Text")
print(fl.closed)
Output:
In the above example, when the statement is executed, it first goes to file_manager class where file_manager object is created to point out the file text.txt as its file name, and mode are initialized to write mode __init__ method is executed. Then the __enter__ method will open the file in the write mode, and it returns the object of class file_manager to the variable fl. Then the content in the text.txt file is written into the file that is opened. Then __exit__ method is called to ensure that the opened file is closed after exiting from with the statement. So the output is true because after with statement, there is a print statement to check if the file is closed using fl.closed as this will be done earlier when with statement is executed and the file is closed, and then it calls __exit__ method.
Implement Context Manager as a Generator
In this way, the Python provides you in-built library known as contextlib for this purpose, so instead of constructing class, we can use this module to implement a context manager.
Example:
from contextlib import contextmanager
@contextmanager
def demo_file(file_name):
fl = open(file_name, 'w')
yield fl
fl.close()
with demo_file("Text.txt") as fl:
fl.write("Educba Training")
From the above example, we use yield to fetch a series of values which means the content of the file is returned to the file which is opened in the write mode.
Conclusion
The context managers are used to manage the resources. In any other languages, file management can be done using try, finally, block but it might give an exception, and again even these are handled, and it might be a practice to say after opening a file it must be closed as there can be resource leakage, but most of the time we forget to do this. In Python, this can be done using the statement. The context managers are implemented in various ways to manage the resources wherewith statement will automatically close the opened files.
Recommended Articles
We hope that this EDUCBA information on “Python Context Manager” was beneficial to you. You can view EDUCBA’s recommended articles for more information.