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
_______________________________________________
DB-SIG maillist  -  DB-SIG@python.org
http://mail.python.org/mailman/listinfo/db-sig

Reply via email to