liveBook · Manning

Context manager

As explained in Coding with AI

A context manager is an object protocol that performs setup on entering a managed block and cleanup when the block exits.

A context manager packages setup and cleanup around a with block. For database work, it opens a SQLite connection before the block and commits and closes it afterward, avoiding repeated manual resource handling. section 5.3.4

import sqlite3

class DatabaseConnection:
    def __init__(self, db_path):
        self.db_path = db_path

    def __enter__(self):
        self.connection = sqlite3.connect(self.db_path)
        return self.connection.cursor()

    def __exit__(self):
        self.connection.commit()
        self.connection.close()

This compact implementation stores the database path, opens SQLite in __enter__, returns a cursor to the block, then commits and closes the connection in __exit__. section 5.3.4

Using a connection in a Flask route

A route can keep database lifetime local to the query: with DatabaseConnection(db_path) as cursor: questions = Questions(cursor) data = questions.fetch_data() return render_template('index.html', data=data) The Questions object receives the cursor, fetches the records, and leaves the connection to the context manager for cleanup. section 5.3.5

Review the implementation before reusing it:

  • Confirm that __enter__ returns the object the block needs; this implementation returns a cursor rather than the connection. section 5.3.4
  • Check the transaction policy: the shown __exit__ commits every completed block before closing the connection. section 5.3.4
  • Reuse the connection wrapper across application code so database access remains easier to test and extend. section 5.3.5

How Coding with AI covers it

How deep it goes
Defines __enter__ and __exit__, explains their execution order, and demonstrates cursor access, commit, and close behavior.
Examples
Uses a DatabaseConnection class, a SQLite questions database, and a Flask index route that renders fetched records.
What it assumes
Assumes basic Python classes, methods, SQLite connections, cursors, and Flask route structure.
What you can do after
Apply it via Python's with statement to scope database access and arrange automatic connection cleanup.
How it connects
Links the with statement to SQLite, database cursors, Flask routes, and data-fetching classes.

Also explained in

Compare how 4 books explain context manager →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Coding with AI. The section links point to the parts of the book it draws on.