Explain context manager. Can you write your own context manager example?

Last updated 3 weeks, 4 days ago | 29 views 75     5

Tags:- Python

Python | context manager

Context managers allow you to allocate and release resources precisely when you want to. The most widely used example of context managers is the with() statement. 

with open('some_file', 'w') as opened_file:

The above code opens the file, writes some data to it, and then closes it. If an error occurs while writing the data to the file, it tries to close it. The above code is equivalent to:

file = open('some_file', 'w')


While comparing it to the first example we can see that a lot of code is eliminated just by using with() statement. The main advantage of using a with statement is that it makes sure our file is closed without paying attention to how the nested block exits.

A common use case of context managers is locking and unlocking resources and closing opened files (as I have already shown you).

Implementing a Context Manager as a Class:

A context manager has an __enter__ and __exit__ method defined. Let’s make our own file-opening Context Manager and learn the basics.

class File(object):
    def __init__(self, file_name, method):
        self.file_obj = open(file_name, method)
    def __enter__(self):
        return self.file_obj
    def __exit__(self, type, value, traceback):

Just by defining __enter__ and __exit__ methods we can use our new class in a with() statement. Let’s try:

with File('test.txt', 'w') as opened_file:

Let’s talk about what happens under-the-hood.

  •     The with statement stores the __exit__ method of the File class.
  •     It calls the __enter__ method of the File class.
  •     The __enter__ method opens the file and returns it.
  •     The opened file handle is passed to opened_file.
  •     We write to the file using .write().
  •     The with statement calls the stored __exit__ method.
  •     The __exit__ method closes the file.