custom context managers

Published 2025-05-14

Context managers are essential for ensuring that resources like files, locks, or network connections are properly released after use, even if errors occur. They’re used with the with statement.

Custom context managers are implemented as classes with an __enter__(self) and an __exit__(self, exc_type, exc_val, exc_tb) method.

the __enter__(self) method:

the __exit__(self, exc_type, exc_val, exc_tb) method:

Example to temporarily change the working directory:

class TemporaryDirectoryChange:
    def __init__(self, new_temporary_path):
        self.new_temporary_path = new_temporary_path
    def __enter__(self):
        self.cwd = os.getcwd()
        os.chdir(self.new_temporary_path)
        print(f"Temporarily changed directory to {self.new_temporary_path}")
        return self
    def __exit__(self, exc_type, exc_val, exc_tb):
        os.chdir(self.cwd)
        print(f"Restored original directory: {self.cwd}")
        return False

Example use:

with TemporaryDirectoryChange(temp_dir_path):
        with open("temp_file.txt", "w") as f:
            f.write("This file is in the temporary directory.")

All actions within the outer with block are performed in the temporary directory. Any actions outside that block are in the current/non-temporary directory, regardless of what happens within that block. Very useful for file safety.