112. contextlib Context Managers

Python's contextlib module provides utilities for working with context managers, which are used for resource management (e.g., opening/closing files, acquiring/releasing locks). You can create custom context managers using contextlib, making your code cleaner and more efficient. Below are examples of how to use contextlib to create and manage custom context managers.


1. Using contextlib.contextmanager to Create a Context Manager

The @contextmanager decorator allows you to create a context manager with a generator.

Copy

from contextlib import contextmanager

@contextmanager
def open_file(file_name, mode):
    file = open(file_name, mode)
    try:
        yield file
    finally:
        file.close()
        print("File closed.")

# Usage
with open_file("example.txt", "w") as f:
    f.write("Hello, contextlib!")

Explanation:

  • The yield statement pauses the function and provides control to the with block.

  • Code after yield ensures cleanup (e.g., closing the file).


2. Custom Context Manager for Logging

Use contextlib.contextmanager to implement a logging context manager.

Copy

Output:

Copy


3. Suppressing Exceptions with contextlib.suppress

The suppress context manager can ignore specified exceptions.

Copy

Explanation:

  • The suppress context manager ignores the specified exception (FileNotFoundError here).


4. Temporary Change with contextlib

Use @contextmanager to temporarily change a variable or system state.

Copy


5. Redirecting Standard Output with redirect_stdout

Redirect the standard output to a file or other writable objects.

Copy


6. Closing Resources Automatically

contextlib.closing is useful when working with objects that have a .close() method.

Copy


7. Nested Context Managers with contextlib.ExitStack

ExitStack allows you to manage multiple context managers dynamically.

Copy

Explanation:

  • ExitStack ensures all opened files are closed, even if an exception occurs.


8. Using contextlib.AsyncExitStack for Async Context Managers

Manage multiple asynchronous context managers.

Copy


9. Custom Context Manager Using contextlib.AbstractContextManager

Define a custom context manager class.

Copy


10. Timeout Context Manager

Implement a context manager for timing out operations.

Copy


Key Features of contextlib:

  1. Efficient Resource Management: Handles setup and teardown cleanly.

  2. Reusable Logic: Custom context managers simplify repetitive operations.

  3. Dynamic Contexts: Use ExitStack for flexible and dynamic context management.

  4. Exception Handling: Automatically suppress or handle exceptions where needed.

These utilities make contextlib a powerful tool for clean, readable, and efficient resource management in Python.

Last updated