[Python-Dev] PEP 310 and exceptions
Nick Coghlan
ncoghlan at gmail.com
Sat Apr 23 05:26:06 CEST 2005
holger krekel wrote:
> Moreover, i think that there are more than the "transactional"
> use cases mentioned in the PEP. For example, a handler
> may want to log exceptions to some tracing utility
> or it may want to swallow certain exceptions when
> its block does IO operations that are ok to fail.
With the current PEP 310 definition, these can be manually handled using
sys.exc_info() in the __exit__ method. Cleaning up my earlier transaction
handler example:
class transaction(object):
def __enter__(self):
begin_transaction()
def __exit__(self):
ex = sys.exc_info()
if ex[0] is not None:
abort_transaction()
else:
commit_transaction()
Alternately, PEP 310 could be defined as equivalent to:
if hasattr(x, '__enter__'):
x.__enter__()
try:
try:
...
except:
if hasattr(x, '__except__'):
x.__except__(*sys.exc_info())
else:
raise
finally:
x.__exit__()
Then the transaction handler would look like:
class transaction(object):
def __enter__(self):
self.aborted = False
begin_transaction()
def __except__(self, *exc_info):
self.aborted = True
abort_transaction()
def __exit__(self):
if not self.aborted:
commit_transaction()
Cheers,
Nick.
--
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
---------------------------------------------------------------
http://boredomandlaziness.skystorm.net
More information about the Python-Dev
mailing list