[Python-Dev] PEP 310 and exceptions
hpk at trillke.net
Sat Apr 23 01:51:12 CEST 2005
probably unsuprisingly i am still pondering the idea of having
an optional __except__ hook on block handlers. The PEP says this
An extension to the protocol to include an optional __except__
handler, which is called when an exception is raised, and which
can handle or re-raise the exception, has been suggested. It is
not at all clear that the semantics of this extension can be made
precise and understandable. For example, should the equivalent
code be try ... except ... else if an exception handler is
defined, and try ... finally if not? How can this be determined
at compile time, in general?
In fact, i think the translation even to python code is not that tricky:
x = X():
basically translates to:
if hasattr(x, '__enter__'):
if hasattr(x, '__except__'): x.__except__(...)
this is the original definition from the PEP with the added
except clause. Handlers are free to call 'self.__exit__()'
from the except clause. I don't think that anything needs to
be determined at compile time. (the above can probably be
optimized at the bytecode level but that is a side issue).
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.
More information about the Python-Dev