[Python-Dev] Merging PEP 310 and PEP 340-redux?

Phillip J. Eby pje at telecommunity.com
Wed May 11 19:43:26 CEST 2005


At 10:00 AM 5/11/2005 -0700, Guido van Rossum wrote:
>(3) Full exception information, with the understanding that when
>__exit__() returns normally, exception processing will resume as usual
>(i.e. __exit__() is called from a finally clause). Exceptions raised
>from __exit__() are considered errors/bugs in __exit__() and should be
>avoided by robust __exit__() methods.

FYI, there are still use cases for clearing the exception state in an 
__exit__ method, that might justify allowing a true return from __exit__ to 
suppress the error.  e.g.:


     class Attempt(object):
         def __init__(self,type,last=False):
             self.type = type
             self.last = last
         def __enter__(self): pass
         def __exit__(self,*exc):
             if exc and not last and issubclass(exc[0],self.type):
                 # suppress exception
                 return True

     def retry(count, type=Exception):
         attempt = Attempt(type)
         for i in range(count-1):
             yield attempt
         yield Attempt(type, True)

     # usage:

     for attempt in retry(3):
         do attempt:
            somethingThatCouldFail()

and:

     class logging_exceptions(object):
         def __init__(self,logger): self.logger = logger
         def __enter__(self): pass
         def __exit__(self,*exc):
             if exc:
                 # log and suppress error
                 self.logger.error("Unexpected error", exc_info=exc)
                 return True

     while True:
         do logging_exceptions(my_logger):
             processEvents()



More information about the Python-Dev mailing list