Table of Contents

import contextlib

import contextlib is a Python import that provides utilities for creating context managers. Use @contextmanager to write with statement handlers for setup/cleanup.

Example

# 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"))

Common functions and decorators