Course contentsShow
← Python
Lesson 620 of 1,06010. Advanced Language FeaturesFree lesson

Implementing Context Managers Using The Dunder Methods

Learners will construct custom classes using enter and exit methods to define initialization and teardown logic for complex resource-handling scenarios.

In this lesson, you will learn how to create your own reusable resource managers by implementing the __enter__ and __exit__ dunder methods in custom classes.

While you are already familiar with using with statements to automate cleanup (like closing files), building your own context managers allows you to encapsulate complex setup and teardown logic—such as opening database connections, managing locks, or timing code blocks—into a clean, readable syntax.

The Dunder Contract

To turn a class into a context manager, it must adhere to the context manager protocol by defining two specific methods:

  1. __enter__(self): This method is triggered when execution enters the with block. Whatever this method returns is assigned to the variable after the as keyword.
  2. __exit__(self, exc_type, exc_val, exc_tb): This method is triggered when execution leaves the with block, even if an exception occurs. The three arguments capture any exception details, allowing you to handle errors gracefully.

Example: A Simple Timer

Here is a class that manages the start and end of a timer, ensuring the elapsed time is printed regardless of how the block finishes:

import time

class Timer:
    def __enter__(self):
        self.start = time.perf_counter()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        end = time.perf_counter()
        print(f"Elapsed time: {end - self.start:.4f} seconds")

# Usage
with Timer():
    # Simulate work
    time.sleep(1)

In this example, as soon as the interpreter hits the with statement, __enter__ starts the clock. When the block finishes—or if an error happens inside—__exit__ immediately calculates the duration and outputs the result. This encapsulates the logic perfectly; you don't have to manually stop the clock or worry about forgetting to print the results, even if an exception occurs within the block.

By defining these methods, you transform your objects into reliable managers that guarantee predictable behavior, keeping your business logic clean and your resource handling bulletproof.

Key Takeaway: By implementing __enter__ and __exit__, you gain fine-grained control over object lifecycle, ensuring that setup and teardown operations occur automatically and safely every time your code enters or leaves a context.