[DB-SIG] Use of context managers with DB API 2

Christoph Zwerschke cito at online.de
Thu Nov 1 15:01:40 CET 2012

We're currently preparing a new release of PyGreSQL and want to make use 
of context managers. My obvious idea was to let connections and cursors 
act as context managers that just close themselves, and add an extra 
context manager in form of a "transaction" property on the connection 
object that can be used to wrap transactions.

However, I then noticed that PySqlite, cx_Oracle, mx_odbc and pyodbc use 
connection as context managers differently, they do not close the 
connection on exit, but execute a rollback or commit instead.

Though I felt a separate context manager for wrapping transactions would 
have been a better solution, I now think I should better follow the 
above examples and wrap transactions in the context manager of the 
connection, it looks like it already has become a quasi standard. Any 
opinions on that or reasons why it has been implemented this way?

-- Christoph

More information about the DB-SIG mailing list