[Zope3-dev] Please, no bare 'except:' clauses!

Jeremy Hylton jeremy@zope.com (Jeremy Hylton)
Mon, 11 Nov 2002 12:43:57 -0500


>>>>> "GvR" == Guido van Rossum <guido@python.org> writes:

  GvR> I would prefer to write that as follows:

  GvR>   txn = a_bdb_transaction() ok = 0 try:
  GvR>     val = do_some_work() ok = 1
  GvR>   finally:
  GvR>     if ok:
  GvR>       txn.commit()
  GvR>     else:
  GvR>       txn.abort()
  GvR>   return val

BTW, here's a higher order transact() function from my LL2 slides.
The idea is that yoiu have some function or method that you want to
execute as a transaction -- call the function spam().  You pass the
function to spam() and use the result.  Example usage:

def spam(...):
    ...

txn_spam = transact(spam)

def transact(f, retries=3):
    def wrapper(*args, **kwargs):
        n = retries
        while n:
            try:
                try:
                    return f(*args, **kwargs)
                finally:
                    get_transaction().commit()
            except ConflictError:
                n -= 1
                if n == 0:
                    raise
            except:
                get_transaction().abort()
                raise
    return wrapper

The txn_spam() function will be executed within a transaction.  If
there are conflicts, it will be tried at most three times.  If an
unexpected error occurs, the transaction will be aborted and the
objects it modified will be reverted to their former state.

Jeremy