What are context managers in Python ?

Posted by Afsal on 17-Jun-2022

Hi Pythonistas

Today we are going the discuss context managers. Context managers are used for managing resources like files, database connections, etc. These resources are a limited number so if we create an object we must explicitly close these objects else it will create errors. 

In python by default, it gives a context manager for files. Context manager can be called using the with statement

Example

with open("file.txt", "w") as f:
    f.write("hello")
print(f.closed)

Output

True

Here the file is closed when the block get executed.

Now we know what is context managers now we can learn how to write a custom context manager, Every context manager has two method they are 

__enter__: This method is called when the objects of manger called when the with statement started. We return the resource object here

__exit__: This method is called just before the exiting the with block

Let us create a custom manager for the file operation

class CustomFileManager:
    def __init__(self, filename, mode):
        self.filename = filename
        self.mode = mode
        self.file = None

    def __enter__(self):
        print("Opening file")
        self.file = open(self.filename, self.mode)
        return self.file

    def __exit__(self, exception_type, exception_value, exception_traceback):
        self.file.close()
        print("File closed")
with CustomFileManager('test.txt', 'w') as f:
    f.write('Test') 
print(f.closed)

Output

Opening file

File closed

True

Here in the  __enter__ method we create a file object and return the file objects. In the __exit__ method, we close the file object.

Use context managers when managing resources this will make code more pythonic and avoid the unwanted issues

Hope you have learned something from this post. Please share your suggestion with afsal@parseltongue.co.in