[Python-ideas] Retrying EAFP without DRY

Chris Rebert pyideas at rebertia.com
Sat Jan 21 09:25:25 CET 2012


On Fri, Jan 20, 2012 at 11:47 PM, Steven D'Aprano <steve at pearwood.info> wrote:
<snip>
> I think that the idiom of a while or for loop is easy enough to read and
> write:
>
> for _ in range(5):  # retry five times
>    try:
>        do_something(x)
>    except SpamError:
>        x = fix_up(x)
>    else:
>        break
> else:
>    raise HamError("tried 5 times, giving up now")
>
>
> I just wish that break and continue could be written outside of a loop, so
> you can factor out common code:

You also seem to have some shenanigans going on with `x`.

> def do_the_thing(x):
>    try:
>        do_something(x)
>    except SpamError:
>        x = fix_up(x)
>    else:
>        break
>
> def try_repeatedly(n, func):
>    for _ in range(n):
>        func()
>    else:
>        raise HamError('tried %d times, giving up now" % n)
>
> try_repeatedly(5, do_the_thing)

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)

Cheers,
Chris



More information about the Python-ideas mailing list