Advanced 12 min

Context managers and resource cleanup

A context manager defines what happens when entering and leaving a block.

How it works

Imagine check-in and check-out around a piece of work. Entering prepares the resource, the block uses it, and exiting releases it. The example uses finally so end appears whenever the block leaves, including when the work raises an error.

Walk through an example

A file’s context manager opens access for the body and closes the file when the with block ends. A lock can use the same pattern to release itself automatically.

What to watch for

A context manager’s exit logic may also run when the body raises an error. Cleanup should release the acquired resource without accidentally suppressing the original failure.

Code example

from contextlib import contextmanager

@contextmanager
def activity():
    print("begin")
    try:
        yield
    finally:
        print("end")

with activity():
    print("work")

Check your understanding

Does leaving the block still close the file?

See the example and explanation
Worked example
Given An exception is raised inside with open(...).
Answer Yes.

The file object’s context manager runs its exit behavior while the exception leaves the block.

Open practice problem
Next lessonAsync tasks and cancellation