Skip to content

Context Manager

with open('sample.txt', 'w') as f:
    f.write('Testing')

What is happening behind (using class):

class Open_file():
    def __init__(self, filename, mode):
        self.filename = filename
        self.mode = mode

    def __enter__(self):
        self.file = open(self.filename, self.mode)
        return self.file

    def __exit__(self, exc_type, exc_val, traceback):
        self.file.close()

What is happening behind (using method):

from contextlib import contextmanager

@contextmanager
def open_file(file, mode):
    try:
        f = open(file, mode)
        yield f
    finally:
        f.close()

In a similar way (using method) we can create our own context managers so that some specific task will execute for sure even if we forget to execute that explicitly.