81. Context Managers with contextlib

Here are 10 Python code snippets demonstrating how to use the contextlib module to create reusable context managers.

1. Using contextlib.contextmanager for Simple Context Managers

This example shows how to create a simple context manager using the @contextmanager decorator.

from contextlib import contextmanager

@contextmanager
def simple_context():
    print("Entering the context")
    yield
    print("Exiting the context")

# Using the context manager
with simple_context():
    print("Inside the context")

2. Managing File Resources with contextlib.closing

The closing context manager is useful for closing resources like network connections or file handles that don't support the with statement natively.

from contextlib import closing
import urllib.request

with closing(urllib.request.urlopen('http://example.com')) as page:
    content = page.read()
    print(content[:100])  # Print the first 100 characters of the page

3. Suppressing Exceptions Using contextlib.suppress

The suppress context manager is used to suppress specified exceptions during execution.


4. Timing a Code Block Using a Context Manager

Creating a custom context manager to measure the execution time of a block of code.


5. Custom Context Manager Using a Class

Implementing a custom context manager using a class with __enter__ and __exit__ methods.


6. Using contextlib.nested for Multiple Contexts

The nested function (deprecated in Python 3.1, replaced by with statements in with statements) allows managing multiple contexts simultaneously.


7. Using contextlib.ExitStack to Handle Multiple Context Managers Dynamically

ExitStack can be used for handling a dynamic number of context managers.


8. Redirecting Standard Output Using contextlib.redirect_stdout

Redirecting standard output to a file or other stream using redirect_stdout.


9. Creating a Context Manager for Database Connections

A context manager for handling database connections.


10. Handling Temporary Directory Creation Using TemporaryContext

Creating and cleaning up a temporary directory with a context manager.


These examples showcase different ways to create and use context managers with the contextlib module, from simple cases using @contextmanager to handling complex resources dynamically with ExitStack.

Last updated