Python Tutorial 0/52 lessons ~6 min read Lesson 36

    Context Managers

    Context managers (the with protocol) guarantee setup/teardown.

    Course progress0%
    Focus
    8 guided sections
    Practice signal
    Examples included
    Career prep
    Foundation builder

    Introduction

    Context managers (the with protocol) guarantee setup/teardown. Implement via __enter__/__exit__ or the @contextmanager decorator.

    Understanding the topic

    Core concepts to understand:

    • with calls __enter__ / __exit__.
    • @contextmanager turns a generator into one.
    • Used for files, locks, DB sessions, timers.
    • __exit__ can suppress exceptions.

    Syntax reference

    Visual flow / code:

    python
    from contextlib import contextmanager
    import time
    @contextmanager
    def timer(label: str):
    start = time.perf_counter()
    try:
    yield
    finally:
    print(f"{label}: {time.perf_counter()-start:.3f}s")
    with timer("db query"):
    run_query()
    # Class-based
    class Connection:
    def __enter__(self):
    self.conn = connect()
    return self.conn
    def __exit__(self, *exc):
    self.conn.close()
    with Connection() as conn:
    conn.execute(...)

    Execution workflow

    1Context Managers Workflow
    1 / 4

    Step 1

    with calls __enter__ / __exit__.

    Apply this step while implementing context managers in real code.

    Real-world use

    Database sessions, file locks, distributed transactions — all use context managers to guarantee cleanup. Critical for resource safety.

    Best practices

    • Prefer @contextmanager for simple cases.
    • Always release resources in __exit__.
    • Use ExitStack for dynamic stacks.

    Hands-on exercise

    Interview preparation — practice these questions:

    • Walk through __enter__/__exit__.
    • @contextmanager — how does it work?
    • What does ExitStack do?

    Summary

    In summary: with = guaranteed cleanup. @contextmanager is the easy way.

    Ready to mark this lesson complete?Track your journey across the entire course.