[Python-Dev] Re: anonymous blocks

Nick Coghlan ncoghlan at gmail.com
Tue Apr 26 23:21:06 CEST 2005

Phillip J. Eby wrote:
> At 09:12 PM 4/24/05 -0600, Steven Bethard wrote:
>> I guess it would be helpful to see example where the looping
>> with-block is useful.
> Automatically retry an operation a set number of times before hard failure:
>     with auto_retry(times=3):
>         do_something_that_might_fail()
> Process each row of a database query, skipping and logging those that 
> cause a processing error:
>     with x,y,z = log_errors(db_query()):
>         do_something(x,y,z)
> You'll notice, by the way, that some of these "runtime macros" may be 
> stackable in the expression.

These are also possible by combining a normal for loop with a non-looping with 
(but otherwise using Guido's exception injection semantics):

def auto_retry(attempts):
     success = [False]
     failures = [0]
     except = [None]

     def block():
             yield None
             failures[0] += 1
             success[0] = True

     while not success[0] and failures[0] < attempts:
         yield block()
     if not success[0]:
         raise Exception # You'd actually propagate the last inner failure

for attempt in auto_retry(3):
     with attempt:

The non-looping version of with seems to give the best of both worlds - 
multipart operation can be handled by multiple with statements, and repeated use 
of the same suite can be handled by nesting the with block inside iteration over 
an appropriate generator.


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

More information about the Python-Dev mailing list