Creating new context manager in Python
What is Context Manager?
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:
- Calling
__enter__()
method
- Whenwith
statement entered, this method will be called
- All the resource initialization will happen
- New object will be returned which will be assinged toas
clause - Executing the block of code after
with
statement
- The code insidewith
will be executed
- If any error/exception, it will call__exit__
method - 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…