Module 14 · Lesson 02
Context Managers and the with Statement
Guarantee clean-up with the with statement: how __enter__ and __exit__ work, what happens on an error, writing managers as classes or with contextlib.contextmanager, and the ready-made ones in contextlib.
- About 9 minutes
- Builds on earlier lessons
- 12-question quiz at the end
What you will learn
- with and a file
- Enter and exit, step by step
- Write one with contextmanager
- Watch the clean-up run
Set up, then always clean up
A with block runs your code between a set-up step and a clean-up step that is guaranteed to happen.
with
with open(...) as f:closes the file when the block ends, even after an error.__enter__
Runs at the start. What it returns is the name after
as.__exit__
Runs at the end, every time, and is told about any error.
contextmanager
A generator with one
yield, plus@contextmanager, makes a manager.
Clean-up everywhere
Anything you must hand back afterwards is a good fit for a with block.
- ConnectionsClose the network connection when the download ends, or when it fails.
- Locks
with lock:lets one thread at a time into a block, and always lets go. - Temporary folders
tempfile.TemporaryDirectory()deletes its folder when the block ends. - Database savesKeep the changes if the block worked, undo them if it failed.
Reading a with line
This line opens a file for writing, inside a managed block. Tap each part to see its job.
Part 1 of 6
with:Starts a managed block. Clean-up is promised when the block ends.
Blocks that clean up after themselves
Pick an example, change it, then press Run. Say what you expect to see before you press.
Example 1 of 6with and a file
The file is open inside the block and closed straight after it.
Your turn: Write a second line to the diary, then read both back.
with open("diary.txt", "w") as f:
f.write("Dear diary\n")
print("inside, closed?", f.closed)
print("after, closed?", f.closed)
with open("diary.txt") as f:
print(f.read())Press Run to see what it prints.Watch set-up and clean-up run
Press Step to run one line at a time. Watch the names box change.
Ready. Press Step to run the first line.
- from contextlib import contextmanager
- def visit(place):
- print("arrive at", place)
- yield place.upper()
- print("leave", place)
- with visit("park") as p:
- print("enjoying the", p)
- print("home")
Output so far
Nothing printed yet.
What Python does
Python reads the program from the top. Nothing has run yet.
Names
None yet.
Quick guesses
Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.
Question 1 of 6
1.What kind of object is f?
with open("a.txt", "w") as f:
pass
print(type(f).__name__)0 of 6 answered
Common with misconceptions
Each card is something learners often believe. Tap it to see what Python really does.
Misconception 1 of 4
Notes
Everything above, in words. Open it when you want the full explanation.
Read the notesNotesOpenClose
Syntax
The general shape of the statements in this lesson.
with manager as value: # value = manager.__enter__()
... # manager.__exit__(...) always runs
class Manager:
def __enter__(self):
return self # what "as" receives
def __exit__(self, exc_type, exc_value, tb):
return False # False: let errors through
from contextlib import contextmanager, suppress
@contextmanager
def manager():
# setup
try:
yield value # the block runs here
finally:
pass # clean-up, even on errors
with suppress(KeyError): # ignore exactly KeyError
...
with a() as x, b() as y: # enter a, b; exit b, a
...Press Run to see what it prints.Worked examples
Read the problem, run the code, then read why it works.
Example 1 of 2
An undo-able change to a shopping basket
Write a context manager class Transaction for a dictionary of stock. Changes made inside the block are kept if the block finishes, and undone if it raises. Show one successful order and one that fails halfway.
class Transaction:
def __init__(self, data):
self.data = data
def __enter__(self):
self.backup = dict(self.data)
return self.data
def __exit__(self, exc_type, exc_value, traceback):
if exc_type is not None:
self.data.clear()
self.data.update(self.backup)
print("rolled back:", exc_value)
return False
stock = {"mug": 5, "lamp": 2}
with Transaction(stock) as s:
s["mug"] -= 2
print("after order 1:", stock)
try:
with Transaction(stock) as s:
s["mug"] -= 1
if s["lamp"] < 3:
raise ValueError("not enough lamps")
s["lamp"] -= 3
except ValueError:
print("order 2 refused")
print("after order 2:", stock)Press Run to see what it prints.Predict first
How it works(open after your guess)
Common pitfalls
Mistakes people make with this topic, and what to write instead.
Pitfall 1 of 3
No finally in a contextmanager
Spot the bug
Can you see what is wrong? Run it to watch it go wrong, then open the fix.
from contextlib import contextmanager
@contextmanager
def connected():
print('connect')
yield
print('disconnect')
try:
with connected():
raise ValueError('bad query')
except ValueError:
print('error handled')Press Run to see what it prints.Show what goes wrong and the fixWhat goes wrong and the fix
In the real world
Where this shows up in software people use every day.
- Software testing
Capturing output in a test
A team tests a command-line report function that prints its results. Their test needs to check exactly what was printed, and must also prove that a temporary working folder is always removed afterwards. Two context managers from the standard library and one of their own handle it.
Why Python fits
redirect_stdoutsends the report's prints into a StringIO buffer for the length of the block, so the test can inspect them. The home-madescratch_foldermanager creates a temporary folder and removes it infinally. Both are entered on onewithline and exited in reverse order, and the checks after the block run on normal output again.Pythonimport contextlib, io, os, shutil, tempfile def print_report(rows): for name, total in rows: print(f"{name:<6}{total:>6}") @contextlib.contextmanager def scratch_folder(): path = tempfile.mkdtemp() try: yield path finally: shutil.rmtree(path) buffer = io.StringIO() with scratch_folder() as folder, contextlib.redirect_stdout(buffer): print_report([("north", 120), ("south", 95)]) with open(os.path.join(folder, "report.txt"), "w") as f: f.write("saved") printed = buffer.getvalue().splitlines() print("captured lines:", printed) print("first line correct:", printed[0] == "north 120") print("folder removed:", not os.path.exists(folder))OutputPress Run to see what it prints.
Key takeaways
Tick each one you could explain to a friend.
0 of 5
Common questions
Guess the answer first, then open it.
Do I still need try and except inside a with block?
Can a with block return a value from a function?
Is a context manager reusable?
What does the as part do if __enter__ returns None?
Your notes
Sign in to keep private notes alongside this lesson.
Where to go next
The quiz and the Lab live on their own pages, so this lesson stays about learning.
Finished this lesson?
Create an ID or sign in to save your progress across devices.
Check what you learned
12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.
Keep going in the Lab
7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.
Spaced review
Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.
This lesson at a glance
The 19 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.
What else you can search for and explore
Curious to go further? Each card opens a web search in a new tab.
References
Look things up here whenever you need the exact details.