[DB-SIG] DB API extension suggestion

Anthony Tuininga anthony.tuininga at gmail.com
Thu Jun 21 18:41:44 CEST 2007


I have been recently playing with context managers and the new "with"
statement added in Python 2.5. I would like to suggest the addition of
the following methods  to connections:

def __enter__(self):
    return self

def __exit__(self, excType, excValue, excTraceback):
    if excType is None and excValue is None and excTraceback is None:
        self.commit()
    else:
        self.rollback()

This allows the following code:

from __future__ import with_statement

connection = .....
with connection:
    cursor = connection.cursor()
    cursor.execute("update SomeTable set SomeColumn = "SomeValue")
    cursor.execute("delete from SomeOtherTable where SomeOtherColumn = 5)


rather than

try:
    cursor = connection.cursor()
    cursor.execute("update SomeTable set SomeColumn = "SomeValue")
    cursor.execute("delete from SomeOtherTable where SomeOtherColumn = 5)
    connection.commit()
except:
    connection.rollback()

I've implemented this in cx_Oracle and it appears to work quite
nicely. Thoughts?

Anthony


More information about the DB-SIG mailing list