Python's with statement

In Python 2.5 there is a new with statement which is really nice to use for transactions. The with statement makes it a lot easier to code try/except/finally statements (the with statement is defined in PEP 343).

The with statement can do wonders to code where transactions are used. An example, instead of writing this:

con1 = users_db(uid)
con2 = users_db(uid)

con1.startTransaction()
con2.startTransaction()

try:
    con1.delete('foo', id=1)
    con2.delete('bas', id=1)
except:
    con1.rollback()
    con2.rollback()
    raise
else:
    con1.commit()
    con2.commit()

You write this:

con1 = users_db(uid)
con2 = users_db(uid)

with transaction(con1, con2):
    con1.delete('timelines', id=1)
    con2.delete('timelines', id=1)

PEP 343 also explains how to implement transaction function that takes a single connection:

from __future__ import with_statement
from contextlib import contextmanager

@contextmanager
def transaction(db):
    db.begin()
    try:
        yield None
    except:
        db.rollback()
        raise
    else:
        db.commit()

The bottom line is use with statement whenever you have try/except/finally - it makes the code much prettier ;-)

17. Jul 2008 Code · Python · Tips
© Amir Salihefendic