import contextlib is a Python import that provides utilities for creating context managers. Use @contextmanager to write with statement handlers for setup/cleanup.
# Python # description: create context managers, suppress exceptions from contextlib import contextmanager, suppress import os # Create context manager from generator @contextmanager def working_directory(path): """Change to directory, then restore.""" old_cwd = os.getcwd() os.chdir(path) try: yield finally: os.chdir(old_cwd) # Use context manager with working_directory("/tmp"): print(os.getcwd()) # /tmp print(os.getcwd()) # back to original # Suppress exceptions with suppress(FileNotFoundError): os.remove("nonexistent.txt") # No error raised # Multiple context managers from contextlib import ExitStack with ExitStack() as stack: f1 = stack.enter_context(open("file1.txt")) f2 = stack.enter_context(open("file2.txt"))
@contextmanager: convert generator to context managercontextlib.suppress(*exceptions): suppress specific exceptionscontextlib.ExitStack(): manage multiple context managerscontextlib.redirect_stdout(file): redirect stdout to filecontextlib.redirect_stderr(file): redirect stderr to file