Site Tools


import-contextlib

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

  • @contextmanager: convert generator to context manager
  • contextlib.suppress(*exceptions): suppress specific exceptions
  • contextlib.ExitStack(): manage multiple context managers
  • contextlib.redirect_stdout(file): redirect stdout to file
  • contextlib.redirect_stderr(file): redirect stderr to file
import-contextlib.md · Last modified: by 127.0.0.1