[Python-ideas] Retrying EAFP without DRY

Nick Coghlan ncoghlan at gmail.com
Sat Jan 21 13:06:11 CET 2012

On Sat, Jan 21, 2012 at 11:40 AM, Bruce Leban <bruce at leapyear.org> wrote:
> while True:
>     try:
>         # block
>     except:
>         # block
>         if condition: continue # retry
>     break

And, indeed, I'd consider "while True" to be a fairly idiomatic way to
write "keep trying this until it works (and we exit the loop via
break) or we give up (and raise an exception)" without repeating
ourselves. Alternatively, I'd push the entire try/except block into a
closure and call that from the loop until it reported it had worked. A
nested generator could achieve much the same thing.

I don't think there needs to be "one obvious way" to do this, since
it's a rare need and the existing tools (while loops with
break/continue, a loop with an appropriate flag, a loop plus a
closure, a nested generator, etc) all provide ways to implement it
reasonably cleanly.


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

More information about the Python-ideas mailing list