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

Chris Clark Chris.Clark at actian.com
Thu Nov 1 16:57:54 CET 2012

On Thursday 2012-11-01 08:57 (-0700), M.-A. Lemburg <mal at egenix.com> wrote:
> Christoph Zwerschke wrote:
>> 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?
> While I'm not much of a fan of using connections as context managers
> (error handling gets tricky), my impression is that most database modules
> implement the rollback/commit approach.
> Cursors are, if implemented, always closed automatically when used as
> context managers. Again, error handling can get tricky because of this,
> but there is definity demand for using both connections and cursors
> as context managers.
> If there's agreement, we could add this kind of use as context managers
> to the DB-API 2.0 as standard extension.

If we do this, we should probably provide pure python reference context 
manager implementations in the spec.


More information about the DB-SIG mailing list