Rana Maninder Singh
Lesson 10 of 11Python Advanced

Context Managers

Lesson opener

In one line: A with block runs setup, runs your code, and runs cleanup even when the block raises.

Why it matters: Northline's file export and a database session both need a guaranteed close or a guaranteed end to the transaction. A close() on the last line does not run if an earlier line raises. Figures are illustrative.

Before this lesson: Functions and exceptions. Generators help you read @contextmanager, but you can learn the with statement first.

What you will be able to do

Prerequisites

Python 3.12. The with statement is specified in https://docs.python.org/3/reference/compound_stmts.html#the-with-statement. @contextmanager is in https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager. The sqlite3 connection behaviour is in https://docs.python.org/3/library/sqlite3.html#how-to-use-the-connection-context-manager.

Setup and cleanup are a pair

Plain English: The object after with is a context manager. Python calls __enter__ at the start and __exit__ at the end. __enter__ returns the value bound by as. __exit__ receives the exception type, the exception, and the traceback, or three Nones if the block succeeded. If __exit__ returns a true value, it suppresses the exception. Return False when the caller should still see the error.

A file object's with closes the file. That is not a universal rule for every library. A sqlite3 connection used as a context manager commits the transaction on success and rolls it back on failure. The same documentation says the connection is not closed by that with. Close it yourself, or write a context manager whose job is to close.

Teacher walkthrough: a session that always logs close

All figures are illustrative.

The export opens, writes one SKU, and must log close even when the write raises.

  1. __enter__ logs open and returns the session.
  2. The block does the work.
  3. __exit__ logs close and returns False.
  4. Validation: a successful block logs open, work, close. A block that raises still logs close, and the exception still propagates.
class Session:
    def __init__(self, events):
        self.events = events

    def __enter__(self):
        self.events.append("open")
        return self

    def __exit__(self, exc_type, exc, tb):
        self.events.append("close")
        return False

events = []
with Session(events) as session:
    session.events.append("work")
assert events == ["open", "work", "close"]

failed = []
try:
    with Session(failed):
        raise RuntimeError("disk")
except RuntimeError:
    pass
assert failed == ["open", "close"]

A second workplace case

contextlib.contextmanager builds the same pair from a generator. Code before yield is setup. Code in finally is cleanup. The sqlite3 example uses the standard-library behaviour: the with commits, and the connection still accepts a query until close().

import sqlite3
from contextlib import contextmanager

@contextmanager
def logged(events):
    events.append("open")
    try:
        yield events
    finally:
        events.append("close")

events = []
with logged(events) as handle:
    handle.append("row")
assert events == ["open", "row", "close"]

conn = sqlite3.connect(":memory:")
with conn:
    conn.execute("create table stock (sku text, qty integer)")
    conn.execute("insert into stock values ('FX-100', 80)")
qty = conn.execute("select qty from stock where sku = 'FX-100'").fetchone()[0]
assert qty == 80
conn.close()

A file opened with with is closed when the block ends:

from pathlib import Path
import tempfile

folder = tempfile.TemporaryDirectory()
path = Path(folder.name) / "stock.txt"
with path.open("w", encoding="utf-8") as handle:
    handle.write("FX-100,80\n")
assert handle.closed
assert path.read_text(encoding="utf-8") == "FX-100,80\n"
folder.cleanup()

Failure example: the handle stayed open, and the sqlite with was treated as a close

Symptom: After an exception, the log has open and not close. A later change wrapped sqlite3.connect in with and removed conn.close(), on the theory that every with closes.

Diagnosis: Cleanup sat after the risky line, so the exception skipped it. The sqlite3 documentation says the connection context manager commits or rolls back and does not close the connection. The root cause is cleanup that is not in __exit__ or finally, plus a borrowed assumption about with.

Correction: Put cleanup in __exit__ or in a finally under @contextmanager. Keep conn.close() unless you have another owner that closes that connection. Do not return True from __exit__ unless you mean to hide the exception.

Validation: The failed session log is open, close. After a successful sqlite with, a SELECT still runs, which shows the connection was not closed by the with. Then close() runs.

import sqlite3

class Session:
    def __init__(self, events):
        self.events = events

    def __enter__(self):
        self.events.append("open")
        return self

    def __exit__(self, exc_type, exc, tb):
        self.events.append("close")
        return False

failed = []
try:
    with Session(failed):
        raise RuntimeError("disk")
except RuntimeError as exc:
    assert str(exc) == "disk"
assert failed == ["open", "close"]

conn = sqlite3.connect(":memory:")
with conn:
    conn.execute("create table stock (sku text)")
    conn.execute("insert into stock values ('FX-100')")
assert conn.execute("select sku from stock").fetchone()[0] == "FX-100"
conn.close()

Guided practice: close a scratch file

Scenario: Write FX-100 into a temporary file using with, then read it back after the block. Figures are illustrative.

Hints:

Complete solution:

Path.open returns a file object. The with closes it. The text is still on disk after the handle is closed. TemporaryDirectory.cleanup removes the folder.

from pathlib import Path
import tempfile

folder = tempfile.TemporaryDirectory()
path = Path(folder.name) / "sku.txt"
with path.open("w", encoding="utf-8") as handle:
    handle.write("FX-100")
assert handle.closed
assert path.read_text(encoding="utf-8") == "FX-100"
folder.cleanup()

Independent practice

Pick one resource you open: a file, or a connection you already know how to close.

Acceptance criteria:

Common mistakes

  • Putting close() after the work, where an exception skips it.
  • Returning True from __exit__ and swallowing a bug.
  • Assuming every library's with closes the object.
  • Yielding more than once in a @contextmanager generator. The helper expects a single yield.

Quick check

  1. Which method runs at the end of a with block?
  2. What does a true return from __exit__ do?
  3. Does a file object's with close the file?
  4. Does with sqlite3 connection commit-or-rollback close the connection?
  5. Where does @contextmanager put the cleanup?

Answers:

  1. __exit__.
  2. It suppresses the exception from the block.
  3. Yes.
  4. No. It commits on success and rolls back on failure. Call close() separately.
  5. In a finally after the single yield.

Quiz alignment

The quiz asks you to guarantee cleanup, to avoid suppressing errors by accident, and to refuse the claim that a sqlite3 connection with closes the connection.

Lesson summary

with pairs setup and cleanup. Files close. Your own __exit__ or finally should close what you opened. A sqlite3 connection with ends the transaction and leaves the connection open.

Bridge to the next lesson

The next lesson writes down the types of these functions so a reader can see what goes in and what comes out, without pretending Python will enforce those notes at runtime. Bring one function whose arguments you can name.