Context Manager Protocol

Python
Author

Imad Dabbura

Published

January 1, 2023

with statement is designed to work with context manager objects to simplify the try/finally pattern, which guarantees that some code is executed (clean up code) after the with block code is aborted because of an exception, a return or sys.exit() call. In a sense, the clean-up that would typically be in the finally clause such as releasing some resources or restoring the temporarily changed state.

Context manager protocol implements __enter__ & __exit__:

class ContextProtocal:
    def __enter__(self):
        # Setup
        # return nothing, i.e. None
        # Or return self
        return self

    def __exit__(self, exc_type, exc_val, traceback):
        # Teardown which should typically handle exceptions
        # to make sure the  Teardown is taken care of even
        # in the case of exceptions
        pass