Creating new context manager in Python

What is Context Manager?

chanduthedev
2 min readSep 13, 2024
  • Context manager is a easy way to maintain resources.
  • It will be used along with with keyword
  • It will automatically handles cleaning up resources after used.
  • One of the best example for context manager is file open given below.
  • We no need to close the file, context manager will take care of closing the file.
with open("sample.txt", "r") as f_obj:
for line in f_obj:
print(line.strip())

Internal Working of a Context Manager

  • A context manager is a construct used to manage resources like files, network connections, and locks. The context manager protocol relies on two special methods __enter_ and __exit__
  • When using a context manager, the with statement essentially does the following:
  1. Calling __enter__() method
    - When with statement entered, this method will be called
    - All the resource initialization will happen
    - New object will be returned which will be assinged to as clause
  2. Executing the block of code after with statement
    - The code inside with will be executed
    - If any error/exception, it will call __exit__ method
  3. Calling __exit__() method to make clean up process
    - This method will call after completing step 2 or any error in step 2
    - This method will clean up(e.g. closing file) all the…

--

--