[Python-ideas] Retrying EAFP without DRY

Nick Coghlan ncoghlan at gmail.com
Tue Jan 24 15:06:23 CET 2012

On Tue, Jan 24, 2012 at 9:36 PM, Paul Moore <p.f.moore at gmail.com> wrote:
> A construct that let end users abstract this type of pattern would
> probably be a far bigger win than a retry statement. (And it may be
> that it has the benefit of already existing, I just couldn't see it
> :-))

You just need to move the pause inside the iterator:

    def backoff(attempts, first_delay, scale=2):
        delay = first_delay
        for attempt in range(1, attempts+1):
            yield attempt
            delay *= 2

    for __ in backoff(MAX_ATTEMPTS, 5):
           response = urllib2.urlopen(url)
       except urllib2.HTTPError as e:
           if e.code == 503:  # Service Unavailable.

You can also design smarter versions where the object yielded is
mutable, making it easy to pass state back into the iterator.


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

More information about the Python-ideas mailing list