Pylerno
English

Context managers

Put setup and cleanup around a block, including its error path.

On this page

The concept

A context manager defines a resource lifetime for with. contextlib.contextmanager lets you express a small context manager using a function and one yield, without writing a class. Code before yield prepares the resource; the yielded value becomes the as target.

Put cleanup in finally so it runs when the block finishes normally or raises an exception. The caller can still handle the error outside the with block. Cleanup is not the same as silently suppressing an exception.

Worked example

python
from contextlib import contextmanager


@contextmanager
def resource(name):
    print("Acquiring:", name)
    try:
        yield name
    finally:
        print("Releasing:", name)


with resource("demo") as name:
    print("Using:", name)
try:
    with resource("failure-demo"):
        raise ValueError("expected failure")
except ValueError:
    print("The caller handled the error")

Trace the result

  1. The normal block acquires, uses, and releases a named demonstration resource.
  2. The failure block raises ValueError deliberately.
  3. Its cleanup still occurs before the outer except handles the error.
text
Acquiring: demo
Using: demo
Releasing: demo
Acquiring: failure-demo
Releasing: failure-demo
The caller handled the error
Line-by-line walkthrough

Line 1: from contextlib import contextmanager

Import contextmanager from contextlib. This supplies resource-lifetime helpers. The caller can now use the imported names directly.

Lines 5–10: def resource(name):

Define the function resource with input names name. Definition stores the operation rather than executing its body. An ordinary call executes a normal function; a coroutine runs when awaited/scheduled, and a generator advances when consumed. Decorators can provide a context-manager or wrapper interface. Indented statements below belong to this operation.

Line 6: print("Acquiring:", name)

Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.

Lines 7–10: try:

Run the protected body. A matching except handles its specified failure. An else suite runs after a successful try body, and finally runs when leaving the construct. This structure should handle expected failures without concealing unrelated bugs.

Line 8: yield name

Yield name to the generator caller and suspend here. The next request resumes the saved execution state.

Cleanup suite: read the statements below as part of this branch.

Line 10: print("Releasing:", name)

Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.

Lines 13–14: with resource("demo") as name:

Enter the listed context manager(s), run the indented block, and leave each context afterward. The manager defines the cleanup/commit behavior; a database transaction and a file lifetime are not identical contracts.

Line 14: print("Using:", name)

Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.

Lines 15–19: try:

Run the protected body. A matching except handles its specified failure. An else suite runs after a successful try body, and finally runs when leaving the construct. This structure should handle expected failures without concealing unrelated bugs.

Lines 16–17: with resource("failure-demo"):

Enter the listed context manager(s), run the indented block, and leave each context afterward. The manager defines the cleanup/commit behavior; a database transaction and a file lifetime are not identical contracts.

Line 17: raise ValueError("expected failure")

Raise ValueError('expected failure'). Normal execution stops here unless an enclosing handler catches it. A from cause, when present, preserves the reason for a translated error.

Handler for ValueError: control reaches this suite only for a matching exception from the protected body.

Line 19: print("The caller handled the error")

Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.

Common mistake

A generator-based context manager should yield exactly once. Accidentally swallowing a block error changes its contract.

Check your understanding

Which method is called when leaving a synchronous with block?

Choose one answer

Search documentation

Share this page