Q&A library Python

What does the with statement (context manager) do in Python?

Python Intermediate context-managerresourceswith

Short answer

The with statement guarantees setup and cleanup around a block, most often closing a file even if an error occurs. It replaces manual try and finally for managing resources.

The short version

The with statement runs a block with guaranteed cleanup afterwards, whether the block finishes normally or raises. Its most common use is opening files: the file is closed automatically when the block ends. It replaces the older pattern of try and finally for managing resources, and it is both shorter and harder to get wrong.

The file case

with open("notes.txt") as f:
    data = f.read()
# the file is closed here, automatically

When the block ends, for any reason, the file is closed. You do not call f.close() yourself, and you cannot forget to.

What it replaces

Without with, safe handling needs try and finally.

f = open("notes.txt")
try:
    data = f.read()
finally:
    f.close()

This is correct but verbose, and it is easy to forget the finally, leaving files open. The with version does the same thing in one line, so prefer it.

Why leaking resources matters

If you open files without closing them, a long-running program accumulates open handles until the operating system refuses more. The same applies to network connections and database sessions. with ties the resource's lifetime to the block, so it is released promptly and reliably.

It works for more than files

Many objects support with, including locks, database connections and network sessions. The pattern is the same: acquire on entry, release on exit.

import threading
lock = threading.Lock()

with lock:
    # critical section, lock is released on exit
    ...

Managing several at once

You can open several resources in one with, separated by commas, and all are cleaned up.

with open("in.txt") as src, open("out.txt", "w") as dst:
    dst.write(src.read())

Writing your own

Any object with __enter__ and __exit__ methods works with with, and the contextlib module makes it easy to build one from a generator using the @contextmanager decorator. You rarely need this for everyday work, but it is how libraries provide clean setup and teardown for their own resources.

Need this solved on your own data?

The library is free and always will be. When the problem is bigger than an answer, we take on the work.

Start a project