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
    Interview Q&A included

    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

    with calls __enter__ / __exit__

    with calls __enter__ / __exit__.

    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.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    3 questions
    1IntermediateQuestionWalk through __enter__/__exit__.+

    Answer

    On with obj as x:, Python calls obj.__enter__() and binds its return value to x. When the block ends, normally or by exception, it calls obj.__exit__(exc_type, exc, tb). If __exit__ returns a true value the exception is suppressed; otherwise it propagates. This is how files, locks, and transactions get reliable cleanup.

    Follow-up

    What is the async equivalent?
    2IntermediateQuestion@contextmanager — how does it work?+

    Answer

    contextlib.contextmanager turns a generator function with a single yield into a context manager. Code before the yield acts as __enter__, the yielded value is bound by as, and code after it acts as __exit__. Exceptions from the block are thrown into the generator at the yield, so wrap it in try/finally to guarantee cleanup.

    Follow-up

    What happens if you forget the try/finally?
    3AdvancedQuestionWhat does ExitStack do?+

    Answer

    contextlib.ExitStack manages a dynamic number of context managers and cleanup callbacks. You register them with enter_context() or callback(), and on exit they are unwound in last-in, first-out order, with exceptions handled as in nested with blocks. It is useful when the number of resources is only known at runtime, or for optional resources.

    Follow-up

    How does pop_all() help with transferring ownership of resources?

    Summary

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

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