Python Context Manager Types

In python, the runtime context is supported by the with statement. The context is defined by the context manager. Using the context manager, we can create user defined classes to define the runtime context. It enters into the task before executing the statement body, and when the statement body is completed, it ends.

There are two different methods for context manager. These methods are −

Method __enter__()

The __enter__() method is used to enter into the runtime context. It will return either the current object or another related object. The returned value is bound to the identifier in as clause of the with statement.

Method __exit__(exc_type, exc_val, exc_tb)

The __exit__() method is used to return a Boolean type result. It indicates any exception that occurred. If there is one exception for the with statement, it will go to the end block.

Example Code

class MyFileManager:
   def __init__(self, fname):
      self.file_name = fname

   def __enter__(self):
      self.myFile = open(self.file_name, 'r')
      return self.myFile

   def __exit__(self, exc_type, exc_val, exc_tb):
      if self.myFile:

   with MyFileManager('sampleTextFile.txt') as myFile:
   x =


Test File.
We can store different contents in this file

Updated on: 25-Jun-2020


Kickstart Your Career

Get certified by completing the course

Get Started