__except__ use cases (was: Re: [Python-Dev] PEP 310 and exceptions)

holger krekel hpk at trillke.net
Sat Apr 23 18:06:49 CEST 2005

On Sat, Apr 23, 2005 at 13:41 +1000, Nick Coghlan wrote:
> Nick Coghlan wrote:
> 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

On a side note, I don't see too much point in having __except__ 
return something when it is otherwise easy to say: 

    def __except__(self, typ, val, tb): 
        raise typ, val, tb 

But actually i'd like to to mention some other than
transaction-use cases for __except__, for example with

    class MyObject: 
        def __except__(self, typ, val, tb): 
            if isinstance(val, KeyboardInterrupt): 
            # process exception and swallow it

you can use it like: 

    x = MyObject(): 
        # do some long running stuff 

and MyObject() can handle internal problems appropriately and
present clean Exceptions to the outside without changing the
"calling side".  With my implementation i also played with
little things like: 
    def __getattr__(self, name): 
            return self._cache[key]

with an obvious __except__() implementation for

Similar to what Alex points out i generally think that being
able to define API/object specific exception handling in *one*
place is a great thing. I am willing to help with the PEP and 
implementation, btw.



More information about the Python-Dev mailing list