[Python-ideas] Retrying EAFP without DRY

Chris Rebert pyideas at rebertia.com
Tue Jan 24 19:01:42 CET 2012


> 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
On Tue, Jan 24, 2012 at 7:21 AM, Jakob Bowyer <jkbbwr at gmail.com> wrote:
> Would this not be better expressed as a context manager?
>
> with backoff(maxattempts, 5):
>    # do stuff

It can't be. The `with` statement always executes its block exactly
once; the context manager(s) have no say in the matter (unless perhaps
you count raising an exception prior to the block's execution).

Cheers,
Chris



More information about the Python-ideas mailing list