[Python-ideas] Retrying EAFP without DRY

Nick Coghlan ncoghlan at gmail.com
Tue Jan 24 02:20:18 CET 2012


On Tue, Jan 24, 2012 at 11:06 AM, Mike Meyer <mwm at mired.org> wrote:
> On Tue, 24 Jan 2012 11:00:53 +1100
> Steven D'Aprano <steve at pearwood.info> wrote:
>> I don't. To me, "retry this thing repeatedly" is fundamentally a loop.
>
> What's being abstracted out isn't "retry this thing repeatedly".  it's
> "I want to retry this thing after tweaking things if it fails." In
> particular, different ways of failure might require different tweaks
> before the retry, second failures would be handled differently from
> first failures, etc.

But that's just normal loop-and-a-half behaviour, where the first half
of the loop is consistent, but the second half depends on the results
of the first half (including whether or not an exception is thrown).

    while attempts_remaining():
        try:
            # attempt consistent operation
        except ExpectedException:
            # set up for next attempt based on result of current attempt
            # even the list of expected exceptions can be made dynamic!
        else:
            break # success!
    else:
        # All attempts failed!

I'm not sure what it is about having an upper limit of 2 iterations,
or having the loop exit criteria be "didn't throw an exception" rather
than an ordinary conditional expression, that makes you feel like this
construct isn't just an ordinary loop-and-a-half (and best thought
about that way).

Cheers,
Nick.

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



More information about the Python-ideas mailing list