Custom Context Managers

intermediate level · ~20 min · Module 14: Context Managers & with

Manage setup and teardown phases cleanly using classes with __enter__ and __exit__ methods.

Learning objectives

  • Understand the protocol behind the with statement
  • Build custom resource managers

Lesson material

The Context Protocol

When a with statement executes, Python calls __enter__ before entering the block and __exit__ when exiting (even if exceptions occur).

Example code

class TimerContext:
    def __enter__(self):
        print("Starting timer...")
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print("Timer stopped.")
        return False

with TimerContext():
    print("Executing work...")

Practice exercise: Custom Managed Resource

Create a context manager class `LoggerCtx` that prints `"ENTER"` in `__enter__` and `"EXIT"` in `__exit__`. Use it with `with LoggerCtx(): print("INSIDE")`.

Test yourself with the Module 14: Context Managers & with quiz →

View the full Python curriculum →