Explain it simply
Explain it simply
Think of borrowing a book from a library: you check it out on the way in and return it when you are done. Now imagine a librarian at the door who takes the book back even if you run out halfway through because your phone rang. The book can never go missing.
Python's with statement is that librarian. Write with open("notes.txt") as f: and the file is always closed when the block ends, whether the code inside finished normally or raised an error. You no longer have to remember the closing step yourself.
Problem → Why → Solution
The problem: an error skips the cleanup
Both snippets below work on the happy path. But if build_report() or update_balance() raises an exception, the close() and release() lines are never reached. The file handle stays open, the lock stays held, and every other thread waiting for that lock blocks forever.
f = open("report.txt", "w")
f.write(build_report()) # raises -> f.close() never runs
f.close()
lock.acquire()
update_balance() # raises -> the lock is never released
lock.release()Why does this happen?
When an exception is raised, Python skips the remaining lines and goes looking for a handler, so a plain cleanup line only runs on the happy path. try/finally fixes it, but you must repeat that pattern every time you use the resource, and forgetting it once brings the leak back. A context manager packages setup and cleanup inside the resource itself, so writing with gives you the finally for free.
Core concept: the with statement protocol
Python runs with EXPR as name: in four steps. It evaluates EXPR to get the context manager object, calls its __enter__() and binds the return value to name, runs the block, and finally calls __exit__() no matter how the block ended. Note that name is whatever __enter__ returns, not necessarily the manager itself; a file's __enter__ returns self, which is why the two look the same.
__exit__(exc_type, exc_value, traceback) receives three arguments. When the block finishes normally all three are None; when it raises, they hold the exception class, the exception object and the traceback. If __exit__ returns a truthy value the exception is suppressed and execution continues after the with statement; if it returns False or None, the exception keeps propagating. That is why the protocol is essentially try: body finally: cleanup.
If a whole class feels heavy, apply the contextlib.contextmanager decorator to a generator function. Code before the yield becomes __enter__, the yielded value becomes the name after as, and code after the yield becomes __exit__. If the body raises, Python throws that exception back into the generator at the yield line, so cleanup that is not inside a finally will be skipped.
You can use several managers at once, as in with a() as x, b() as y:. They are entered left to right and exited in reverse order, like a stack. The standard library ships many ready-made ones, including contextlib.suppress, ExitStack, threading.Lock and sqlite3 connections.
| Manager | as receives | __exit__ cleans up by |
|---|---|---|
| open(path) | the file object itself | closing the file |
| threading.Lock() | True | releasing the lock |
| sqlite3 connection | the connection itself | committing or rolling back (not closing) |
| contextlib.suppress(E) | None | swallowing exceptions of type E only |
- __enter__ sets up, returns the as-value
- The with body runs
- __exit__ always runs, like finally
- Only a True return hides an exception
Whenever you see with, mentally rewrite it as "try: body / finally: __exit__".
General pattern
class ManagerName:
def __enter__(self):
return value_for_as # setup
def __exit__(self, exc_type, exc_value, traceback):
return False # cleanup; False = re-raise
@contextmanager
def manager_name(args): # setup goes first
try:
yield value_for_as
finally:
pass # cleanupThe class form needs two methods; in the function form a single yield splits enter from exit. Either way you use it as with manager_name(args) as name:.
Example: a class-based and a function-based manager
The Resource class prints when it opens and closes, so you can see exactly when __exit__ runs. In the second with block a ValueError is raised, yet the "close" line appears before the outer except catches it. The last part does the same kind of job with @contextmanager.
from contextlib import contextmanager
class Resource:
"""A class-based context manager: __enter__ sets up, __exit__ cleans up."""
def __init__(self, name):
self.name = name
def __enter__(self):
print(f"open {self.name}")
return self # this object is bound to the name after "as"
def __exit__(self, exc_type, exc_value, traceback):
error = exc_type.__name__ if exc_type else "none"
print(f"close {self.name} (error: {error})")
return False # False = let any exception keep travelling
with Resource("report.txt") as res:
print(f"using {res.name}")
try:
with Resource("data.csv"):
raise ValueError("bad row 7")
except ValueError as e:
print(f"caught outside the with block: {e}")
@contextmanager
def tag(name):
print(f"<{name}>") # setup: everything before yield
try:
yield
finally:
print(f"</{name}>") # cleanup: runs even after an exception
with tag("p"):
print("hello")Code breakdown
- __enter__
return self # this object is bound to the name after "as"Whatever __enter__ returns is bound to res. Returning self is the most common choice, but any object is allowed.
- __exit__ arguments
def __exit__(self, exc_type, exc_value, traceback):In the first block exc_type is None, so it prints "error: none"; in the second it is the ValueError class, so it prints "error: ValueError".
- Re-raise
return False # False = let any exception keep travellingReturning False lets the ValueError travel out of the with block, where the try/except catches it. Had it returned True, the "caught outside" line would never print.
- @contextmanager
try: yield finally: print(f"</{name}>") # cleanup: runs even after an exceptionEverything before yield prints <p>, then the body runs. Because the closing print sits in finally, </p> appears even if the body raises.
open report.txt
using report.txt
close report.txt (error: none)
open data.csv
close data.csv (error: ValueError)
caught outside the with block: bad row 7
<p>
hello
</p>- Create the manager object
- Call __enter__() and bind as
- Run the body
- Call __exit__()
Body succeeds
__exit__(None, None, None) runs, then the next line
Body raises
__exit__ gets the exception; it re-raises unless True
A timer, exit order and suppress
The Timer class stores the elapsed time in __exit__ and does not swallow exceptions. time.perf_counter() is more precise than time.time() for measuring short durations. The printed time varies from run to run.
import time
class Timer:
def __enter__(self):
self.start = time.perf_counter()
return self
def __exit__(self, exc_type, exc_value, traceback):
self.elapsed = time.perf_counter() - self.start
return False
with Timer() as t:
total = sum(i * i for i in range(100_000))
print(f"total={total}, took {t.elapsed:.4f}s") # the time varies per runWith two managers in one with statement, they are entered left to right and exited right to left. contextlib.suppress() deliberately swallows only the exception types you name, which is the safe, explicit version of an __exit__ that returns True.
from contextlib import contextmanager, suppress
@contextmanager
def step(name):
print("enter", name)
try:
yield
finally:
print("exit", name)
with step("outer"), step("inner"):
print("body")
with suppress(FileNotFoundError):
open("missing-file.txt")
print("still running")In real projects
Where this shows up in real projects
You meet with wherever a resource must be given back after use: open files, database transactions, thread locks, network connections. with conn: commits an sqlite3 transaction on success and rolls it back on error, and with lock: releases a lock even when an exception is raised. A requests.Session used as with requests.Session() as s: closes its connection pool at the end.
Tests use them constantly: unittest.mock.patch() swaps a function for a fake only inside the with block and restores the original on the way out, and tempfile.TemporaryDirectory() deletes its scratch folder when the test ends. Teams write their own timers, logging contexts and temporary-setting helpers with @contextmanager, and test that cleanup happens on both the success path and the failure path.
Common mistakes
Common mistakes
1. Returning True from __exit__ casually
Returning True makes every exception in the block vanish, even a NameError caused by a typo. If you really mean to swallow one kind of exception, check exc_type before returning True, or use contextlib.suppress().
2. Forgetting try/finally in @contextmanager
If the cleanup simply follows the yield, an exception from the body surfaces at the yield line and skips it. Always put the yield inside try and the cleanup inside finally.
3. Using the resource after the block
Calling f.read() after with open(path) as f: has ended raises ValueError: I/O operation on closed file. The name f still exists, but the file is closed. Read what you need inside the block and keep it in a variable.
4. Assuming with conn: closes the connection
An sqlite3 connection's with only commits or rolls back the transaction; it does not close the connection. Call conn.close() yourself or wrap it in contextlib.closing(conn). Check the documentation for what each manager actually cleans up.
Best practices
Best practices
- Use with for anything that must be closed, released or restored, instead of hand-writing try/finally.
- Prefer @contextmanager for simple managers and write a class when there is real state or reuse.
- Avoid raising a new exception inside __exit__, because it hides the original error.
- When the number of managers is only known at runtime, such as a list of files, use contextlib.ExitStack.
Mini challenge
Mini challenge: a temporary setting override
Write an override() context manager with @contextmanager that sets one key of a dict to a new value only inside the with block, then restores the original state when the block exits, even after an error.
- If the key already existed, put its old value back afterwards
- If the key did not exist, delete it afterwards
- Restore even when the body raises, and let the exception propagate
- Yield the dict so it can be used with as
from contextlib import contextmanager
_MISSING = object() # a marker meaning "the key was not there before"
@contextmanager
def override(settings, key, value):
# TODO: remember the old value (or _MISSING), then set the new value
# TODO: yield settings inside a try block
# TODO: in finally, restore the old value or delete the key
...
config = {"debug": False}
# TODO: override "debug" to True; print config inside and after the block
# TODO: override a NEW key "timeout", raise RuntimeError inside the block,
# catch it outside, and print config to show "timeout" is goneExpected: Output: inside: {'debug': True} after: {'debug': False} inside: {'debug': False, 'timeout': 1} error: request failed after error: {'debug': False}
Show hint
settings.get(key, _MISSING) returns the marker when the key is absent, so it cannot be confused with a real value of None. Test it with is _MISSING.
Show solution
from contextlib import contextmanager
_MISSING = object()
@contextmanager
def override(settings, key, value):
old = settings.get(key, _MISSING)
settings[key] = value
try:
yield settings
finally:
if old is _MISSING:
del settings[key]
else:
settings[key] = old
config = {"debug": False}
with override(config, "debug", True):
print("inside:", config)
print("after:", config)
try:
with override(config, "timeout", 1):
print("inside:", config)
raise RuntimeError("request failed")
except RuntimeError as e:
print("error:", e)
print("after error:", config)Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- with calls __enter__, binds the result to as, runs the body, then always calls __exit__.
- An exception disappears only if __exit__ returns a truthy value, so do that only on purpose.
- In @contextmanager, code before the yield is setup and code in finally is cleanup.
- Several managers exit in the reverse of the order they entered.
Python Documentation — Functional Programming HOWTO — Python Software Foundation