Bug in Python 1.5.2 exception handling?
Tim Peters
tim_one at email.msn.com
Fri Dec 17 03:08:17 EST 1999
[Dave Cole, suprised by locals surviving exit-by-exception]
> ...
> The reason that I was worried about this was that I am doing some
> database stuff using my Sybase module:
>
> plug: http://www.itga.com.au/~djc/sybase.html
>
> I wanted to automatically rollback a transaction when an exception
> was raised during processing. I made a class like this:
>
> class Transaction:
> def __init__(self, db, name):
> self.db = db
> self.name = name
> self.db.execute('begin transaction %s' % (self.name,))
> self.commit = 0
>
> def __del__(self):
> if self.commit:
> self.db.execute('commit transaction %s' % (self.name,))
> else:
> self.db.execute('rollback transaction %s' % (self.name,))
>
> Then I thought that all I would have to do was:
>
> def something_or_other(self):
> tran = Transaction(self.db, 'update_id')
> # lots o' database stuff
> tran.commit = 1
>
> I suppose it will still work for the rollback case, but just not
> when I expect it to.
I doubt you want to chance that.
def something_or_other(self):
tran = Transaction(self.db, 'update_id')
try:
# lots o' database stuff
tran.commit = 1
finally:
tran.dispose() # contains what __del__ does now
is reliable under CPython or JPython. I wish there were an even simpler way
to write these kinds of acquire/release pairs, but for now this is as good
as it gets. It's not like it's *un*readable! Quite clear, actually. I
think it's just the "extra" indentation that irks me.
whitespace-is-a-precious-commodity-ly y'rs - tim
More information about the Python-list
mailing list