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():
        try:
            yield None
        except:
            failures[0] += 1
        else:
            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:
        do_something_that_might_fail()


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.


Cheers,
Nick.

--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---------------------------------------------------------------
            http://boredomandlaziness.skystorm.net
_______________________________________________
Python-Dev mailing list
Python-Dev@python.org
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com

Reply via email to