[Python-Dev] PEP 310 and exceptions
Nick Coghlan
ncoghlan at gmail.com
Sat Apr 23 05:41:57 CEST 2005
Nick Coghlan wrote:
> 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__()
>
In light of Alex's comments, I'd actually like to suggest the below as a
potential new definition for PEP 310 (making __exit__ optional, and adding an
__else__ handler):
if hasattr(x, '__enter__'):
x.__enter__()
try:
try:
# Contents of 'with' block
except:
if hasattr(x, '__except__'):
if not x.__except__(*sys.exc_info()): # [1]
raise
else:
raise
else:
if hasattr(x, '__else__'):
x.__else__()
finally:
if hasattr(x, '__exit__'):
x.__exit__()
[1] A possible tweak to this line would be to have it swallow the exception by
default (by removing the conditional reraise). I'd prefer to make the silencing
of the exception explicit, by returning 'True' from the exception handling, and
have 'falling off the end' of the exception handler cause the exception to
propagate.
Whichever way that point goes, this definition would allow PEP 310 to handle
Alex's example of factoring out standardised exception handling, as well as the
original use case of resource cleanup, and the transaction handling:
class transaction(object):
def __enter__(self):
begin_transaction()
def __except__(self, *exc_info):
abort_transaction()
def __else__(self):
commit_transaction()
Cheers,
Nick.
--
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
---------------------------------------------------------------
http://boredomandlaziness.skystorm.net
More information about the Python-Dev
mailing list