[Python-ideas] Retrying EAFP without DRY

Jakob Bowyer jkbbwr at gmail.com
Tue Jan 24 16:21:19 CET 2012


Would this not be better expressed as a context manager?

with backoff(maxattempts, 5):
    # do stuff

Sent from my iPad

On 24 Jan 2012, at 14:06, Nick Coghlan <ncoghlan at gmail.com> wrote:

> 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
>            time.sleep(delay)
>            delay *= 2
> 
>    for __ in backoff(MAX_ATTEMPTS, 5):
>       try:
>           response = urllib2.urlopen(url)
>       except urllib2.HTTPError as e:
>           if e.code == 503:  # Service Unavailable.
>               continue
>           raise
>       break
> 
> You can also design smarter versions where the object yielded is
> mutable, making it easy to pass state back into the iterator.
> 
> Cheers,
> Nick.
> 
> -- 
> Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas



More information about the Python-ideas mailing list