The with Statement in Depth
Understand how with works and why it prevents resource leaks.
The with Statement in Depth is a free Python Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Python Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Introduction
Basic with Usage
with open('/tmp/cm_test.txt','w') as f:
f.write('hello')
print('file closed:', f.closed)Why with Exists
# Without with:
# f = open('f.txt')
# try: ...
# finally: f.close()
# With with:
# with open('f.txt') as f: ...
print('with is cleaner')Multiple Context Managers
import tempfile, os
a = tempfile.mktemp(); b = tempfile.mktemp()
with open(a,'w') as fa, open(b,'w') as fb:
fa.write('A'); fb.write('B')
os.unlink(a); os.unlink(b)
print('both closed')with Does Not Suppress Exceptions
try:
with open('/nonexistent.txt') as f:
pass
except FileNotFoundError as e:
print('caught:', e)Lock as Context Manager
import threading
lock = threading.Lock()
with lock:
print('locked section')
print('lock released')Database Connection Pattern
# Typical DB pattern:
# with db.transaction() as conn:
# conn.execute(sql)
# commits on success, rolls back on exception
print('db pattern demo')Nested with Statements
import tempfile
tmp = tempfile.mktemp()
with open(tmp,'w') as outer:
with open(tmp,'r+') as inner:
outer.write('x')
import os; os.unlink(tmp)
print('nested exit order')contextlib.suppress
from contextlib import suppress
with suppress(FileNotFoundError):
open('/does/not/exist.txt')
print('no error raised')contextlib.redirect_stdout
from contextlib import redirect_stdout
import io
buf = io.StringIO()
with redirect_stdout(buf):
print('captured')
print('got:', buf.getvalue())ExitStack
from contextlib import ExitStack
import tempfile, os
with ExitStack() as stack:
files = [stack.enter_context(open(tempfile.mktemp(),'w')) for _ in range(3)]
for f in files: f.write('x')
print('all closed')Quick Check
Recap
Keep Going
Frequently asked questions
Is the “The with Statement in Depth” lesson free?
Yes — the full text of “The with Statement in Depth” is free to read here on the web, and the Python Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Python Academy course, upgrade to CoddyKit PRO.
What will I learn in “The with Statement in Depth”?
Understand how with works and why it prevents resource leaks. You practise Python Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Python Academy?
No prior experience is required. Python Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “The with Statement in Depth” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Python Academy lesson?
Yes. Every Python Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- The with Statement in Depth
- __enter__ and __exit__ Protocol
- contextlib: @contextmanager
- Practical Context Manager Patterns