You have already used with open(...) as f: to make sure a file is closed. That with statement works with any context manager: an object that sets something up when the block starts and cleans it up when the block ends, even if an error happens in between. This lesson shows how with works, how to write your own context managers as a class or with @contextmanager, and the helpers in contextlib.
In this lesson you will learn
- What the
withstatement guarantees - Writing a context manager class with
__enter__and__exit__ - How exceptions pass through
__exit__ - Writing one as a generator with
@contextmanager contextlib.suppressandExitStack
The Protocol: __enter__ and __exit__
class Timer:
def __init__(self, label):
self.label = label
def __enter__(self):
print(f"[{self.label}] start")
return self # bound to the name after "as"
def __exit__(self, exc_type, exc, tb):
print(f"[{self.label}] end, error: {exc_type.__name__ if exc_type else None}")
return False # False: let any exception continue
with Timer("load") as t:
print("working inside", t.label)
try:
with Timer("parse"):
int("abc")
except ValueError:
print("ValueError still reached the caller")
with open("demo.txt", "w") as f:
f.write("hello")
print("closed after with?", f.closed)
import os; os.remove("demo.txt")
Output
[load] start
working inside load
[load] end, error: None
[parse] start
[parse] end, error: ValueError
ValueError still reached the caller
closed after with? True
- When the
withblock starts, Python calls__enter__; its return value is assigned to the name afteras. - When the block ends, for any reason, Python calls
__exit__. It receives the exception type, value and traceback, or threeNonevalues if the block finished normally. - In the second block,
int("abc")raisesValueError;__exit__still runs and prints the error type. Because it returnsFalse, the exception continues to the surroundingtry. ReturningTruewould swallow it, which is rarely what you want. - File objects are context managers, which is why the file is closed after the
withblock, as in File Handling.
@contextmanager and contextlib Helpers
from contextlib import contextmanager, suppress, ExitStack
import os
@contextmanager
def temp_setting(settings, key, value):
old = settings.get(key)
settings[key] = value # code before yield = __enter__
try:
yield settings
finally:
settings[key] = old # code after yield = __exit__, always runs
config = {"debug": False}
with temp_setting(config, "debug", True) as c:
print("inside:", c)
print("after:", config)
with suppress(FileNotFoundError): # ignore one specific error
os.remove("does-not-exist.txt")
print("no crash")
names = ["a.txt", "b.txt"]
with ExitStack() as stack: # manage a variable number of files
files = [stack.enter_context(open(n, "w")) for n in names]
for f in files:
f.write("data")
print([f.closed for f in files])
for n in names:
os.remove(n)
Output
inside: {'debug': True}
after: {'debug': False}
no crash
[True, True]
@contextmanagerturns a generator function into a context manager. Code beforeyieldis the setup, the yielded value goes toas, and code afteryieldis the cleanup.- Put the cleanup in
finally, otherwise it is skipped when the block raises an exception. suppress(FileNotFoundError)ignores one specific exception type; it is a tidy replacement fortrywith an emptyexcept.ExitStackmanages a number of context managers decided at run time, such as a list of files, and closes all of them at the end.
Where Context Managers Are Used
| Context manager | Setup | Cleanup |
|---|---|---|
open(path) | Open the file | Close it |
threading.Lock() | Acquire the lock | Release it |
sqlite3.connect(db) | Start a transaction | Commit, or roll back on error |
tempfile.TemporaryDirectory() | Create a folder | Delete it |
unittest.mock.patch(...) | Replace an object | Restore the original |
Several context managers can share one statement: with open("a") as a, open("b") as b:.
Common Mistakes
- Cleanup outside
finallyin a@contextmanagerfunction, so it is skipped on errors. - Returning
Truefrom__exit__by accident and hiding real errors. - Using the resource after the block, such as reading from a closed file.
- Yielding more than once in a
@contextmanagergenerator, which raisesRuntimeError.
Practice Exercises
Exercise 1. Write a context manager changed_dir(path) that switches to a folder and switches back afterwards.
Show answer
import os
from contextlib import contextmanager
@contextmanager
def changed_dir(path):
old = os.getcwd()
os.chdir(path)
try:
yield
finally:
os.chdir(old)
Python 3.11 added contextlib.chdir, which does the same thing.
Exercise 2. Use suppress to convert a list of strings to integers, skipping any that are not numbers.
Show answer
from contextlib import suppress
result = []
for s in ["10", "x", "25"]:
with suppress(ValueError):
result.append(int(s))
print(result) # [10, 25]
Frequently Asked Questions
Is with just a shortcut for try/finally?
Essentially, yes. A with block behaves like calling setup, running the body in try, and running cleanup in finally, but the setup and cleanup live in one reusable object.
Are there async context managers?
Yes. Objects with __aenter__ and __aexit__ are used with async with inside async functions, for example for network connections.
Summary
withguarantees cleanup when a block ends, even after an error.- A class context manager defines
__enter__and__exit__. @contextmanagerbuilds one from a generator; put cleanup infinally.suppressandExitStackhandle common patterns.
Next: Python Unit Testing.
