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

Nick Coghlan ncoghlan at gmail.com
Mon Mar 28 08:06:38 CEST 2011


On Mon, Mar 28, 2011 at 1:15 PM, Mike Meyer <mwm at mired.org> wrote:
> 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.

If you want a loop, write a loop.

for fname in possible_fnames:
  try:
    f = open(fname)
  except IOError:
    continue
  break
else:
  raise RuntimeError("Could not open any of {}".format(possible_fnames))
with f:
  # Do stuff

Turning the above into a custom "open_any" context manager is trivial.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia



More information about the Python-ideas mailing list