Python Context Managers
A context manager sets something up, lets your code use it, and then reliably tears it down — even if an error happens in between. You use one every time you write with open(...) as f:. The with statement guarantees the clean-up step runs.
Why with?
Without with, you'd need try/finally to be safe:
f = open("data.txt", encoding="utf-8")
try:
data = f.read()
finally:
f.close() # runs even if read() failsWith a context manager, the same guarantee takes one line:
with open("data.txt", encoding="utf-8") as f:
data = f.read()
# f is closed here, no matter what happenedCommon context managers in the standard library:
| Context manager | Sets up / tears down |
|---|---|
open(...) |
opens / closes a file |
threading.Lock() |
acquires / releases a lock |
decimal.localcontext() |
changes / restores decimal precision |
contextlib.suppress(...) |
ignores chosen exceptions |
contextlib.redirect_stdout(...) |
captures print output |
tempfile.TemporaryDirectory() |
creates / deletes a temp folder |
Writing a class-based context manager
Any object with __enter__ and __exit__ methods works with with:
__enter__(self)runs at the start; its return value is bound to the name afteras.__exit__(self, exc_type, exc, tb)runs at the end. If an exception occurred, the three arguments describe it; otherwise they're allNone.
class Section:
def __init__(self, title):
self.title = title
def __enter__(self):
print(f"=== {self.title} ===")
return self
def __exit__(self, exc_type, exc, tb):
status = "ok" if exc_type is None else f"failed: {exc}"
print(f"=== end {self.title} ({status}) ===")
return False # don't swallow exceptions
with Section("Setup"):
print("installing...")
try:
with Section("Deploy"):
print("uploading...")
raise RuntimeError("server unreachable")
except RuntimeError:
print("handled outside the with block")=== Setup ===
installing...
=== end Setup (ok) ===
=== Deploy ===
uploading...
=== end Deploy (failed: server unreachable) ===
handled outside the with block
If __exit__ returns True, the exception is suppressed. Returning False (or None) lets it propagate, which is almost always what you want.
The easy way: @contextmanager
The contextlib.contextmanager decorator turns a generator into a context manager. Code before yield is the setup, the yielded value is what as receives, and code after yield is the teardown. Wrap the yield in try/finally so teardown runs even on errors:
from contextlib import contextmanager
@contextmanager
def temporary_setting(settings, key, value):
old = settings[key]
settings[key] = value
try:
yield settings
finally:
settings[key] = old
config = {"debug": False, "level": 1}
with temporary_setting(config, "debug", True) as c:
print("inside:", c)
print("after: ", config)inside: {'debug': True, 'level': 1}
after: {'debug': False, 'level': 1}
A file example with clean-up
Here a context manager creates a scratch file and guarantees it's deleted afterwards (in the browser this uses Pyodide's in-memory file system; on your computer it creates exceltad_demo.txt in the current folder and removes it):
import os
from contextlib import contextmanager
@contextmanager
def scratch_file(name):
with open(name, "w", encoding="utf-8") as f:
f.write("temporary data\n")
try:
yield name
finally:
os.remove(name)
print("cleaned up", name)
with scratch_file("exceltad_demo.txt") as path:
with open(path, encoding="utf-8") as f:
print("read:", f.read().strip())
print("exists inside?", os.path.exists(path))
print("exists after? ", os.path.exists("exceltad_demo.txt"))read: temporary data
exists inside? True
cleaned up exceltad_demo.txt
exists after? False
Handy tools from contextlib
import io
from contextlib import suppress, redirect_stdout
with suppress(KeyError):
del {}["missing"] # error silently ignored
print("still running")
buffer = io.StringIO()
with redirect_stdout(buffer):
print("captured text")
print("buffer holds:", repr(buffer.getvalue()))still running
buffer holds: 'captured text\n'
Multiple context managers
One with can manage several resources; they're exited in reverse order:
with open("input.txt", encoding="utf-8") as src, open("output.txt", "w", encoding="utf-8") as dst:
dst.write(src.read().upper())Tip: Whenever you write code that must "always undo" something — close, release, restore, delete — consider packaging it as a context manager.
Test yourself
Which two methods make a class usable in a with statement?
- __open__ and __close__
- __enter__ and __exit__
- __start__ and __stop__
- __init__ and __del__
In a @contextmanager generator, what does the code after yield do?
- Runs before the with-block
- Runs as the clean-up when the with-block ends
- Never runs
- Runs only on errors
What happens if __exit__ returns True?
- The with-block is repeated
- The exception (if any) is suppressed
- The file is deleted
- Nothing special