Python - Context Managers (with)

Overview

Estimated time: 25–35 minutes

Context managers ensure resources are acquired and released safely. Learn the mental model behind with, custom context managers, and powerful tools in contextlib.

Learning Objectives

  • Use with to manage files and other resources safely.
  • Implement custom context managers with classes or @contextmanager.
  • Leverage ExitStack for dynamic, multiple contexts.

Prerequisites

  • Exceptions and functions

Examples

# Always closes the file
with open("hello.txt", "w", encoding="utf-8") as f:
    f.write("Hello")

Guidance & Patterns

from contextlib import contextmanager

@contextmanager
def show_time(label):
    import time
    start = time.perf_counter()
    try:
        yield
    finally:
        dur = time.perf_counter() - start
        print(f"{label}: {dur:.3f}s")

with show_time("work"):
    sum(range(100000))

Best Practices

  • Use ExitStack for conditional resources and to flatten deeply nested with blocks.
  • Ensure contexts handle exceptions correctly; consider idempotent cleanup.

Exercises

  1. Write a context manager that temporarily changes the working directory.
  2. Use ExitStack to manage an unknown set of file handles.