'__enter__' and '__exit__' context managers in python


'__enter__' and '__exit__' context managers in python

__enter__ and __exit__are built in methods in python. __enter__ and __exit__ methods are also called as context manager special methods in python. You may come up with the question"what is a context manager ?". A context manager is a manager which has the ability to make avail the data withing the context or within a block of code and destroy it when it is used. We implement context manager functionality using "with" keyword in python programming. 

Why do we use "with" keyword in python ?

  • "with" keyword is super awesome trick to implement resource management patterns.
  • Resources many be one of "files", "locks", "network connections", etc.

Let's see how to work with keyword "with" in python.

# file resource management without using context managers
file = open('sample.txt', 'w')
try:
	file.write('Python is super awesome!')
finally:
	file.close()

# file resource management without using context managers
with open('sample.txt', 'w') as file:
	file.write('Python is super awesome!')

In the above code, In the first case we have opened a text file named "sample.txt" and wrote some text in it after we closed the file. But in the second case we have implemented the same functionality by using keyword "with". In the first case we have managed opening and closing of the resource file. In the second case (i.e using "with" keyword) the resource management handled autmatically. Python simplified the syntax for first use case scenario with context managers using keyword "with". It is a resuable code pattern. 

You may araise a question "how the closed automatically ?". Actually nothing is automated in any software/program unless we do. If we see the internal implementation of the "open" keyword it looks like below.

import io

class open(object):
    def __init__(self, file_name, mode='r'):
        print('__init__ called')
        self.file_name = file_name
        self.mode = mode

    def __enter__(self):
        print('__enter__ called')
        self.file = io.open(self.file_name, self.mode)
        return self.file

    def __exit__(self, exc_type, exc_value, traceback):
        print('__exit__ called')
        self.file.close()
# lets test it
with open('sample.txt', 'w') as f:
    f.write('hello')
# output
# __init__ called
# __enter__ called
# __exit__ called

In above code we have successfully replicated the working of the "open" keyword in python when it is used with the keyword "with" by using the special methods "__enter__", "__exit__" in python context managers. 

In the method "__exit__"  we have parameters "exc_type", "exc_value" and "traceback" if any exception happens inside the "with" block then we can handle it in this method. Try to implement your own context manager objects and let me know if you get any doubt's or suggestions in the below comments.

Reference: https://docs.python.org/3/library/contextlib.html

Read Next: method overloading in python

Read Prev: model serializers in Django Rest Framework

Blog Archive