Skip to content

Enhance sqlite3 connection context management documentation with contextlib.closing #109234

@d33bs

Description

@d33bs

This issue covers an opportunity to enhance the existing sqlite3 docs on context management by adding a mention of contextlib.closing to help guide developers when performing singular transactions. Adding this section to the documentation would help guide developers in use cases where they'd like to close the sqlite3 connection without an additional sqlite.connect().close() after a context manager closes.

For default sqlite3 context management cases which don't use contextlib.closing we could outline or strengthen existing mention that the intention is to perform multiple transactions without fully closing the connection. This might help distinguish development options / decision-making for Python developers reading through the documentation.

A contextlib.closing example we could include:

import sqlite3
from contextlib import closing

with closing(sqlite3.connect("workfile.sqlite")) as cx:
    with cx:
        cx.execute("CREATE TABLE lang(id INTEGER PRIMARY KEY, name VARCHAR UNIQUE)")
        cx.execute("INSERT INTO lang(name) VALUES(?)", ("Python",))

# no need to close the connection as contextlib.closing closed it for us

Related to a discussion from discuss.python.org. Many thanks to @erlend-aasland for suggesting the contextlib.closing approach and the others in the discussion thread for their help in discussing this topic.

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    Status

    Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions