What is context manager in Python?

In any programming language, we use system resources like for file operations or database connections. But these resources are limited in supply so they must be released after their usage; else they lead to resource leakage and causes system slowdown or crashing.

To facilitate this, Python provides a context manger. Context manager allows us to allocate and release resources precisely when we want to. The most widely used context manager in Python is the ‘with’ statement. When context managers are evaluated it should result in an object that performs context management. Context managers can be written using classes or functions (with decorators).

# context manager class
class File(object):
    # initialize and open the file
    def __init__(self, file_name, method):
        self.file_obj = open(file_name, method)
    # perform the task specified by with context manager
    # here write Hello in the file  
    def __enter__(self):
        return self.file_obj
    # exit method in context manager
    def __exit__(self, type, value, traceback):

# load and perform tasks on file
with File("file1.txt", "w") as opened_file:

On the given file management by context manager and with statement, the following operations happen in sequence:

  1. A File object is created with file1.txt as the filename and ‘write’ (w) mode is assigned
  2. The __enter__ method opens the file in write mode and returns the File object to opened_file.
  3. The text ‘Hello!’ is written into the file.
  4. The __exit__ method takes care of closing the file on exiting the with block.

Real Life Scenario of Context Manager

As we have discussed here, the real life example of context manager is File management for most of the time. But context manager can also be used for Database connection management as well.