Course contentsShow
← Python
Lesson 373 of 1,0606. Error Handling and File I/OFree lesson

Creating Custom Context Managers with Classes

Learners will define the __enter__ and __exit__ methods to build reusable custom logic for managing external resource acquisition and cleanup.

In this lesson, you will learn how to encapsulate resource management logic into a reusable class by defining the __enter__ and __exit__ magic methods.

The Mechanics of the Context Manager

While try...finally blocks are excellent for cleaning up resources, they can become repetitive if you perform the same setup and teardown tasks across your codebase. A custom context manager class allows you to bundle this logic into a clean, reusable interface using the with statement.

To build one, your class must implement two specific methods:

  1. __enter__: This method runs when execution enters the with block. Whatever it returns is assigned to the variable after the as keyword.
  2. __exit__: This method runs automatically when the block finishes, even if an error is raised. It receives details about any exceptions that occurred, allowing you to handle them gracefully.

A Practical Example

Imagine you want a logger that prints a message whenever a block of code starts and finishes.

class SimpleLogger:
    def __enter__(self):
        print("Starting task...")
        return "Task initialized"

    def __exit__(self, exc_type, exc_val, exc_tb):
        print("Cleaning up resources.")
        # If we return False (or nothing), exceptions propagate normally
        return False

# Using the custom context manager
with SimpleLogger() as status:
    print(f"Status: {status}")
    # Perform work here...

When Python hits the with statement, it calls __enter__. Once the indented block completes—or if an exception occurs—it calls __exit__. This ensures your "cleanup" logic is never skipped, which is vital for closing database connections, unlocking files, or resetting state.

By defining these methods, you turn your objects into formal context managers, making your code significantly more readable and robust. You are essentially creating a template that ensures your resources are handled safely every single time they are accessed, without needing to rewrite the try...finally boilerplate each time.

Key Takeaway: By implementing __enter__ and __exit__ in a class, you create a powerful, reusable "wrapper" that ensures resources are consistently acquired and safely cleaned up, regardless of whether your code succeeds or fails.