[Python-ideas] Retry clause (was: Extending error handling on with statements.)

Mike Meyer mwm at mired.org
Mon Mar 28 05:15:25 CEST 2011


On Sun, 27 Mar 2011 22:33:52 +0100
Jakob Bowyer <jkbbwr at gmail.com> wrote:

> I personally love using with statements when handling file like objects.
> This is all well and good until an exception is thrown from the with
> statement. This is ok if you expect the exception because you can use try
> and except but personally I feel that another condition to with would feel
> more 'pythonic' this means that you could fail the with statement with an
> exception jump to the clause, then jump back to the with statement trying
> the code in the clause e.g. rather than

The idea of exception handlers "jumping back" is actually good enough
to have been implemented in one language (eiffel), but sufficiently
different from what "except" does that I think it calls for new
syntax.

How about a "retry" clause for try statements? I think it runs into
the same problems as an "except" clause when it comes to adding it to
the with clause, so lets skip that for now.

retry ...: as part of a try clause would work just like an except
clause: if the exception was one of those listed after retry, then
you'd enter the block following the retry, otherwise you skip it. If
the retry block raises an exception or hits "return" or "yield", it
behaves just like an except block. If the retry block executes it's
last statement, it then branches back to the first statement of the
"try" block.

This would let you write something like:

i = 0
try:
    with open("tmpname.%d" % i, 'r') as inp:
     ....
retry IOError:
   if IOError.errno != ENOENT:
      raise
   i += 1
   if i > 100:
      raise

To search for a file.

   <mike
-- 
Mike Meyer <mwm at mired.org>		http://www.mired.org/consulting.html
Independent Software developer/SCM consultant, email for more information.

O< ascii ribbon campaign - stop html mail - www.asciiribbon.org



More information about the Python-ideas mailing list