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:
- executes when entering the
withblock - performs any necessary initial actions
- the value returned by
__enter__is assigned to the variable afterasin thewithstatement, such asfileinwith open(...) as file - if an error occurs in
__enter__,__exit__is not called
the __exit__(self, exc_type, exc_val, exc_tb) method:
- executes when exiting the
withblock, regardless of what happened (exception or otherwise) within that block - performs any necessary closing actions
- arguments (all are
Noneif no exception occurred):exc_type: the type of the exceptionexc_val: the exception instanceexc_tb: a traceback
- return values:
True: the exception (if any) has been handled, and Python should suppress itFalseorNone: the exception (if any) will be re-raised after__exit__completes (this is standard)
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 FalseExample 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.