Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Statements and Keywords

The with statement

Reference for the Python with statement: run setup and cleanup automatically, use several managers at once, and understand __enter__, __exit__ and suppressed errors.

The with statement runs a block of code between a setup step and a guaranteed cleanup step. The object after with is a context manager: Python calls its __enter__() method before the block and its __exit__() method afterward, even when the block raises an exception or executes return.

It is the standard way to handle files, locks, database transactions and temporary state, because it makes forgetting the cleanup impossible.

Python
with open("notes.txt") as f:
    text = f.read()
# the file is closed here

Try it

Python Files and in-memory buffers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Writing a context manager

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
with expression as target:
    block

with a() as x, b() as y:
    block

with (
    a() as x,
    b() as y,
):
    block
Part Description
expression Evaluates to a context manager, an object with __enter__() and __exit__().
as target Optional. Receives the return value of __enter__() (not necessarily the manager itself).
Multiple items Entered left to right and exited in reverse order. The parenthesized form is officially supported from Python 3.10.

How it works: __exit__(exc_type, exc, traceback) receives None, None, None on a clean exit. If it returns a true value, the exception is suppressed; otherwise it propagates after cleanup.

Raises: TypeError (or AttributeError in older versions) if the object is not a context manager.

Usage notes

  • as is optional. Use it only if you need the object __enter__() returns.
  • Exit order. With several managers, the last one entered is exited first, like nested with blocks.
  • The target stays bound after the block ends. A closed file object is still a valid name, just unusable.
  • Never swallow by accident. A __exit__ that returns a truthy value hides every exception, including bugs. Return True only for errors you mean to handle.
  • @contextmanager from contextlib builds a manager from a generator with one yield; wrap it in try/finally so cleanup runs on errors.
  • Async version. async with uses __aenter__() and __aexit__() inside coroutines.
  • Beyond files: threading.Lock, tempfile.TemporaryDirectory, decimal.localcontext, unittest.mock.patch and database connections all work with with.
  • contextlib.ExitStack handles a variable number of managers.