[Python-Dev] "with" use case: replacing a file

Nick Coghlan ncoghlan at gmail.com
Fri May 13 00:12:00 CEST 2005


Phillip J. Eby wrote:
> Really, the only use case for suppressing exceptions is to, well, suppress 
> exceptions that are being logged, shown to the user, sent via email, or 
> just plain ignored.  Guido's point, I think, is that these use cases are 
> rare enough (yet simple and similar enough) that they don't deserve support 
> from the cleanup facility, and instead should use a try/except block.

Particularly since the *action* can be factored out into a do statement - it's 
only the *suppression* that has to be reproduced inline. That is:

   try:
       do standard_reaction():
           pass
   except MyException:
       pass

> After reviewing the cases in my own code where I might've used a 'with 
> logged_exceptions()' or similar blocks, I think I now agree.

I think I'm convinced, too. The only actual use case in the PEP is auto_retry, 
and that can be more obviously written with a try/except block inside the loop:

   for retry in reversed(xrange(num_attempts)):
       try:
          make_attempt()
          break
       except IOError:
          if not retry:
              raise

Not as pretty perhaps, but the control flow is far easier to see.

Steven has also convinced me that break, continue and return should look like 
normal exits rather than exceptions. This should bring my next PEP draft back to 
something resembling Guido's option 3 - the __exit__() method still gets passed 
the contents of sys.exc_info(), it just can't do anything about it other than 
raise a different exception.

Cheers,
Nick.

P.S. The points regarding non-local flow control in Joel Spolsky's latest Joel 
on Software article (especially the links at the end) may have had something to 
do with my change of heart. . .


-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://boredomandlaziness.blogspot.com


More information about the Python-Dev mailing list