Python Academy · Lesson

The with Statement in Depth

Understand how with works and why it prevents resource leaks.

Lesson 1 of 414 steps

The with Statement in Depth is a free Python Academy lesson on CoddyKit. This is 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, and your progress syncs across the web and the CoddyKit app. The Python Academy course includes 4 lessons in total.

Introduction

The with statement guarantees setup and teardown code runs, even when exceptions occur.

Basic with Usage

with expr as var: — expr must return a context manager. var is bound to whatever __enter__ returns.
with open('/tmp/cm_test.txt','w') as f:
    f.write('hello')
print('file closed:', f.closed)

Why with Exists

Resources like files, locks, DB connections must be released. With guarantees cleanup even if an exception interrupts the body.
# 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

with open(a) as f, open(b) as g: opens two resources in one statement. Both are closed on exit.
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

By default, exceptions in the with body propagate. __exit__ can suppress them by returning True.
try:
    with open('/nonexistent.txt') as f:
        pass
except FileNotFoundError as e:
    print('caught:', e)

Lock as Context Manager

threading.Lock() works as a context manager: with lock: ensures the lock is always released.
import threading
lock = threading.Lock()
with lock:
    print('locked section')
print('lock released')

Database Connection Pattern

A DB connection as a context manager commits on success and rolls back on exception — a critical 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

Nested with statements are fine. The inner context manager exits first, then the outer.
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

contextlib.suppress(ExcType) silently swallows a specific exception type inside the with block.
from contextlib import suppress
with suppress(FileNotFoundError):
    open('/does/not/exist.txt')
print('no error raised')

contextlib.redirect_stdout

contextlib.redirect_stdout(f) redirects print() output to f temporarily.
from contextlib import redirect_stdout
import io
buf = io.StringIO()
with redirect_stdout(buf):
    print('captured')
print('got:', buf.getvalue())

ExitStack

contextlib.ExitStack manages a dynamic number of context managers — useful when you don't know how many files to open.
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

What does contextlib.suppress(FileNotFoundError) do?

Recap

with guarantees cleanup. Multiple targets in one with. contextlib.suppress silences specific errors. ExitStack manages dynamic numbers of context managers.

Keep Going

Great work! The next lesson awaits.
Free to start

Learn Python with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
76
Lessons
320

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. 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. The Python Academy course includes 4 lessons in total.

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, so you can start here or from the beginning and move at your own pace. This is lesson 1 of 4.

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

  1. The with Statement in Depth
  2. __enter__ and __exit__ Protocol
  3. contextlib: @contextmanager
  4. Practical Context Manager Patterns
← Back to Python Academy