[Python-ideas] Retrying EAFP without DRY

Steven D'Aprano steve at pearwood.info
Sat Jan 21 09:57:16 CET 2012


Chris Rebert wrote:
> On Fri, Jan 20, 2012 at 11:47 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> <snip>
>> I just wish that break and continue could be written outside of a loop, so
>> you can factor out common code:
[...]
> Easily accomplished:
> 
> def do_the_thing(x):
>     try:
>         do_something(x)
>     except SpamError:
>         fix_up(x)
>         return False
>     else:
>         return True
> 
> def try_repeatedly(n, func, arg):
>    for _ in range(n):
>        if func(arg): break
>    else:
>        raise HamError('tried %d times, giving up now" % n)
> 
> try_repeatedly(5, do_the_thing, y)

Not so easily accomplished if you need the return result from do_the_thing. 
Naturally you can always return a tuple

(result_I_actually_want, code_to_break_or_continue)

but that's not exactly elegant.




-- 
Steven




More information about the Python-ideas mailing list