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.
with open("notes.txt") as f: text = f.read() # the file is closed here
Try it
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.
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
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
asis 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
withblocks. - 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. ReturnTrueonly for errors you mean to handle. @contextmanagerfromcontextlibbuilds a manager from a generator with oneyield; wrap it intry/finallyso cleanup runs on errors.- Async version.
async withuses__aenter__()and__aexit__()inside coroutines. - Beyond files:
threading.Lock,tempfile.TemporaryDirectory,decimal.localcontext,unittest.mock.patchand database connections all work withwith. contextlib.ExitStackhandles a variable number of managers.