Skip to content

Context Managers

Medium ~35 min

What you'll build

A Timer context manager (class-based) and a file-processing context manager (decorator-based) that handle setup, teardown, and exceptions.

Goals

  • Implement __enter__ and __exit__ methods
  • Use contextlib.contextmanager for decorator-based managers
  • Handle exceptions in __exit__
  • Understand the with statement's guarantees

Prerequisites

  • Classes and __init__
  • try/finally for cleanup
  • The with statement

Steps

  1. 1

    Write a class-based Timer

    A context manager class implements __enter__ (setup, returns the resource) and __exit__ (teardown, handles exceptions). Write a Timer that measures the time inside the with block.

    Code
    import time
    
    class Timer:
        def __enter__(self):
            self.start = time.perf_counter()
            return self
        
        def __exit__(self, exc_type, exc_val, exc_tb):
            self.elapsed = time.perf_counter() - self.start
            print(f"Elapsed: {self.elapsed:.4f}s")
            return False  # don't suppress exceptions
    
    with Timer() as t:
        sum(range(1_000_000))
    # prints 'Elapsed: 0.0x s'

    Expected result

    After the with block, the elapsed time is printed.

  2. 2

    Handle exceptions in __exit__

    If an exception occurs inside the with block, __exit__ receives the exception info. Return True to suppress it, False to propagate. Test both behaviors.

  3. 3

    Use contextlib.contextmanager

    The @contextmanager decorator turns a generator function into a context manager. yield marks the point where the with block runs. Code before yield is setup; after is teardown.

    Code
    from contextlib import contextmanager
    
    @contextmanager
    def open_db(url):
        print(f"Connecting to {url}")
        conn = {"url": url, "open": True}  # mock connection
        try:
            yield conn
        finally:
            conn["open"] = False
            print(f"Closing {url}")
    
    with open_db("localhost:5432") as db:
        print(f"Using {db['url']}, open={db['open']}")
    # prints: Connecting, Using, Closing

    Expected result

    Setup runs before the block, teardown runs after (even on exception).

  4. 4

    Nest context managers

    You can nest with statements to manage multiple resources. Python 3.10+ allows parentheses for multi-line nesting. Test nested timers and connections.

  5. 5

    Build a temporary directory manager

    Write a context manager that creates a temp directory, yields its path, and removes it (with all contents) on exit. Use tempfile and shutil for the implementation.

    Code
    import tempfile, shutil, os
    from contextlib import contextmanager
    
    @contextmanager
    def temp_dir():
        path = tempfile.mkdtemp()
        try:
            yield path
        finally:
            shutil.rmtree(path)
    
    with temp_dir() as d:
        print(f"Working in {d}")
        with open(os.path.join(d, "file.txt"), "w") as f:
            f.write("hello")
    # directory and file are now gone

    Expected result

    The temp directory exists inside the block and is removed after.

Try it yourself

What you learned

You built context managers — Python's RAII mechanism for resource management. They guarantee cleanup even on exceptions, and are used for files, locks, DB connections, and more.

Related Resources

Related Lessons

  • Classes

    Class-based context managers use dunder methods.

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to topic