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

M.-A. Lemburg mal at egenix.com
Thu Nov 1 16:43:06 CET 2012


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.

-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source
>>> Python/Zope Consulting and Support ...        http://www.egenix.com/
>>> mxODBC.Zope.Database.Adapter ...             http://zope.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ...        http://python.egenix.com/
________________________________________________________________________

::: Try our new mxODBC.Connect Python Database Interface for free ! ::::


   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
    D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
           Registered at Amtsgericht Duesseldorf: HRB 46611
               http://www.egenix.com/company/contact/


More information about the DB-SIG mailing list