with statement

Resources

Under the hood, this is what happens, the __exit__ method is called when the with block is completed.

class FileManager:
    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_value, traceback):
        self.file.close()
 
# using the custom context manager
with FileManager('example.txt', 'w') as file:
    file.write('Hello, World!')