Code of the Day
IntermediateIdioms & structure

Context managers

Guarantee setup and cleanup with the with statement.

PythonIntermediate7 min read
Recommended first
By the end of this lesson you will be able to:
  • Use with to manage resources safely
  • Explain why with cleans up even when errors occur
  • Recognise common context managers

Some resources must be cleaned up: files closed, locks released, connections returned. Forgetting is easy, and an partway through makes it worse. The with statement is a that guarantees cleanup happens — even if something fails — making it the Pythonic way to handle the side-effect edges from the systems-thinking lesson.

The with statement

The classic example is files. with opens the file, gives it to you, and closes it automatically when the block ends:

with open("data.txt") as f:
    contents = f.read()
# f is guaranteed closed here, even if read() raised

Compare the manual version you'd otherwise need — open, then try/finally to close — and you see why with exists: it bakes the cleanup in so you can't forget it.

Why it's safe under errors

The promise of a context manager is that its cleanup runs on the way out no matter how you leave the block — normal completion or an exception. That's exactly what you want for resources: a crash mid-read still closes the file, a crash mid-transaction still releases the lock.

Python — editable, runs in your browser

Common context managers

You'll meet them everywhere once you notice the pattern:

  • with open(...) — files.
  • with lock: — releasing a threading lock.
  • Database connections and transactions.
  • with blocks in testing (e.g. asserting an exception is raised).

Whenever you acquire something that must be released, look for a with form first. Reaching for manual try/finally cleanup is a sign there may be a context manager that already does it correctly.

Where to go next

Last in this module: type hints — optional annotations that make Python code safer and clearer.

Finished reading? Mark it complete to track your progress.

On this page