140. Creating and Handling Custom Context Managers

In Python, context managers are a great way to manage resources such as file handles, network connections, or database connections that need to be acquired and released properly. Using contextlib, you can define reusable context managers without needing to implement the __enter__ and __exit__ methods manually. Here's how you can create and handle custom context managers using the contextlib module.

1. Basic Context Manager with contextlib.contextmanager

You can create a custom context manager using the @contextmanager decorator from contextlib.

Copy

from contextlib import contextmanager

@contextmanager
def my_open_file(file_name, mode):
    print(f"Opening file: {file_name}")
    file = open(file_name, mode)
    try:
        yield file  # Provides control back to the with statement
    finally:
        file.close()
        print(f"Closing file: {file_name}")

# Using the custom context manager
with my_open_file('test.txt', 'w') as file:
    file.write("Hello, world!")

Output:

Copy

Explanation:

  • The @contextmanager decorator simplifies the creation of context managers.

  • The yield keyword returns control to the with statement block, and the finally block ensures that resources are cleaned up (in this case, the file is closed).

2. Context Manager for Database Connections

A custom context manager for managing database connections can be created as follows.

Copy

Output:

Copy

Explanation:

  • The context manager ensures that the database connection is opened and closed properly, handling exceptions if any occur during the execution of database operations.

3. Custom Context Manager for Timer

You can create a context manager to measure the time taken by a code block.

Copy

Output:

Copy

Explanation:

  • The context manager timer() measures the time before and after the code block inside the with statement, then prints the time taken.

4. Context Manager with Custom Exception Handling

Context managers can also be used for custom exception handling.

Copy

Output:

Copy

Explanation:

  • The custom context manager exception_handler() catches specific exceptions and handles them within the with block, providing graceful error handling.

5. Context Manager for Resource Locking

A context manager can manage resource locking to ensure that only one thread or process accesses a resource at a time.

Copy

Output:

Copy

Explanation:

  • The context manager locked_resource() acquires a lock before entering the with block and releases it afterward, ensuring safe access to shared resources.

6. Context Manager with Multiple Resources

You can use a context manager to manage multiple resources simultaneously.

Copy

Output:

Copy

Explanation:

  • This context manager acquires multiple resources, yields them to the with block, and releases them afterward.

7. Context Manager for Logging

A context manager can be used to log the entry and exit of a function.

Copy

Output:

Copy

Explanation:

  • The context manager log_function() logs entry and exit messages, useful for tracing the execution of functions.

8. Context Manager for File Backup

This context manager creates a backup of a file before making changes.

Copy

Output:

Copy

9. Context Manager with Configuration Changes

A context manager can temporarily change configuration settings.

Copy

Output:

Copy

10. Context Manager for Network Resource

A context manager for managing network resources, such as opening and closing a socket connection.

Copy

Output:

Copy

Explanation:

  • This context manager manages a network socket connection, ensuring that it is opened before the with block and properly closed afterward.


Conclusion:

Custom context managers using the contextlib module provide a flexible way to manage resources, handle exceptions, and ensure proper cleanup in Python. You can use them to simplify the resource management process in your applications, making the code more readable and maintainable.

Last updated