Contextlib2: Enhanced Context Management

21.6.0 · maintenance · verified Thu Apr 09

Contextlib2 provides backports and enhancements for Python's standard `contextlib` module, offering features like `ExitStack` and `asynccontextmanager` to older Python versions. The current version is 21.6.0, released in June 2021. The project appears to be in maintenance mode, as most of its key features are now integrated into the standard library for Python versions 3.7 and newer.

Warnings

Install

Imports

Quickstart

This example demonstrates `ExitStack` to manage multiple context managers dynamically. It opens several files and ensures they are all properly closed upon exiting the `with` block, even if errors occur.

from contextlib2 import ExitStack
import os

def open_files(filenames):
    with ExitStack() as stack:
        files = [stack.enter_context(open(fname, 'r')) for fname in filenames]
        yield files

# Example usage (will create dummy files first)
if __name__ == '__main__':
    # Create dummy files
    with open('file1.txt', 'w') as f: f.write('Hello from file 1')
    with open('file2.txt', 'w') as f: f.write('Hello from file 2')

    try:
        with open_files(['file1.txt', 'file2.txt']) as opened:
            for i, f in enumerate(opened):
                print(f"Content of file {i+1}: {f.read()}")
    finally:
        os.remove('file1.txt')
        os.remove('file2.txt')

view raw JSON →