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@contextmanagerdefsimple_context():print("Entering the context")yieldprint("Exiting the context")# Using the context managerwithsimple_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 closingimport urllib.requestwithclosing(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.
from contextlib import suppress
with suppress(FileNotFoundError):
# If the file doesn't exist, it will be suppressed
open('non_existing_file.txt', 'r')
print("Program continued without exception.")
import time
from contextlib import contextmanager
@contextmanager
def timer():
start = time.time()
yield
end = time.time()
print(f"Code block executed in {end - start:.4f} seconds")
# Using the timer context manager
with timer():
time.sleep(1) # Simulate a delay
class MyContextManager:
def __enter__(self):
print("Entering context")
return self
def __exit__(self, exc_type, exc_value, traceback):
print("Exiting context")
# Using the context manager
with MyContextManager():
print("Inside the context")
from contextlib import nested
with nested(open('file1.txt', 'r'), open('file2.txt', 'r')) as (f1, f2):
print(f1.read())
print(f2.read())
from contextlib import ExitStack
with ExitStack() as stack:
file1 = stack.enter_context(open('file1.txt', 'r'))
file2 = stack.enter_context(open('file2.txt', 'r'))
print(file1.read())
print(file2.read())
from contextlib import redirect_stdout
with open('output.txt', 'w') as f:
with redirect_stdout(f):
print("This will be written to the file.")
import sqlite3
from contextlib import contextmanager
@contextmanager
def open_db(db_name):
conn = sqlite3.connect(db_name)
try:
yield conn
finally:
conn.close()
# Using the database connection context manager
with open_db('my_database.db') as db:
cursor = db.cursor()
cursor.execute('SELECT * FROM my_table')
print(cursor.fetchall())
import tempfile
import os
from contextlib import contextmanager
@contextmanager
def temporary_directory():
temp_dir = tempfile.mkdtemp()
try:
yield temp_dir
finally:
os.rmdir(temp_dir)
# Using the temporary directory context manager
with temporary_directory() as temp_dir:
print(f"Temporary directory created: {temp_dir}")