[Python-Dev] Re: anonymous blocks

Steven Bethard steven.bethard at gmail.com
Mon Apr 25 05:12:47 CEST 2005


Guido van Rossum wrote:
[snip illustration of how generators (and other iterators) can be
modified to be used in with-blocks]
> the most common use case should not be an alternate looping syntax
> (even though it *is* technically a loop) but a more general "macro
> statement expansion"

I'm sure I could get used to it, but my intuition for

   with f = with_file(filename):
       for line in f:
           print process(line)

is that the f = with_file(filename) executes only once.  That is, as
you said, I don't expect this to be a looping syntax.  Of course, as
long as the generators (or other objects) here yield only one value
(like with_file does), then the with-block will execute only once. 
But because the implementation lets you make the with-block loop if
you want, it makes be nervous...

I guess it would be helpful to see example where the looping
with-block is useful.  So far, I think all the examples I've seen have
been like with_file, which only executes the block once.  Of course,
the loop allows you to do anything that you would normally do in a
for-loop, but my feeling is that this is probably better done by
composing a with-block that executes the block only once with a normal
Python for-loop.

I'd almost like to see the with-block translated into something like

   it = EXPR
   try:
       VAR = it.next()
   except StopIteration:
       raise WithNotStartedException
   err = None
   try:
       BODY
   except Exception, err: # Pretend "except Exception:" == "except:"
       pass
   try:
       it.next_ex(err)
   except StopIteration:
       pass
   else:
       raise WithNotEndedException

where there is no looping at all, and the iterator is expected to
yield exactly one item and then terminate.  Of course this looks a lot
like:

   it = EXPR
   VAR = it.__enter__()
   err = None
   try:
       BODY
   except Exception, err: # Pretend "except Exception:" == "except:"
       pass
   it.__exit__(err)

So maybe I'm just still stuck on the enter/exit semantics. ;-)

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


More information about the Python-Dev mailing list