[Python-Dev] Re: anonymous blocks

Phillip J. Eby pje at telecommunity.com
Thu Apr 28 03:00:01 CEST 2005

At 05:19 PM 4/27/05 -0700, Guido van Rossum wrote:
> > This also has the benefit of making the delineation between template blocks
> > and for loops more concrete.  For example, this:
> >
> >      block open("filename") as f:
> >          ...
> >
> > could be an immediate TypeError (due to the lack of a __resume__) instead
> > of biting you later on in the block when you try to do something with f, or
> > because the block is repeating for each line of the file, etc.
>I'm not convinced of that, especially since all *generators* will
>automatically be usable as templates, whether or not they were
>intended as such. And why *shouldn't* you be allowed to use a block
>for looping, if you like the exit behavior (guaranteeing that the
>iterator is exhausted when you leave the block in any way)?

It doesn't guarantee that, does it?  (Re-reads PEP.)  Aha, for *generators* 
it does, because it says passing StopIteration in, stops execution of the 
generator.  But it doesn't say anything about whether iterators in general 
are allowed to be resumed afterward, just that they should not yield a 
value in response to the __next__, IIUC.  As currently written, it sounds 
like existing non-generator iterators would not be forced to an exhausted 

As for the generator-vs-template distinction, I'd almost say that argues in 
favor of requiring some small extra distinction to make a generator 
template-safe, rather than in favor of making all iterators 
template-promiscuous, as it were.  Perhaps a '@block_template' decorator on 
the generator?  This would have the advantage of documenting the fact that 
the generator was written with that purpose in mind.

It seems to me that using a template block to loop over a normal iterator 
is a TOOWTDI violation, but perhaps you're seeing something deeper here...?

More information about the Python-Dev mailing list