[Python-Dev] Re: anonymous blocks

Steven Bethard steven.bethard at gmail.com
Mon Apr 25 07:51:46 CEST 2005


On 4/24/05, Phillip J. Eby <pje at telecommunity.com> 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)

Thanks for the examples!  If I understand your point here right, the
examples that can't be easily rewritten by composing a
single-execution with-block with a for-loop are examples where the
number of iterations of the for-loop depends on the error handling of
the with-block.  Could you rewrite these with PEP 288 as something
like:

    gen = auto_retry(times=3)
    for _ in gen:
        try:
            do_something_that_might_fail()
        except Exception, err: # Pretend "except Exception:" == "except:"
            gen.throw(err)

    gen = log_errors(db_query())
    for x,y,z in gen:
        try:
            do_something(x,y,z)
        except Exception, err: # Pretend "except Exception:" == "except:"
            gen.throw(err)

Obviously, the code is cleaner using the looping with-block.  I'm just
trying to make sure I understand your examples right.

So assuming we had looping with-blocks, what would be the benefit of
using a for-loop instead?  Just efficiency?  Or is there something
that a for-loop could do that a with-block couldn't?

STeVe
-- 
You can wordify anything if you just verb it.
        --- Bucky Katt, Get Fuzzy


More information about the Python-Dev mailing list