[Python-Dev] pre-PEP: Resource-Release Support for Generators

Phillip J. Eby pje at telecommunity.com
Mon Sep 15 11:26:27 EDT 2003


At 11:48 AM 9/15/03 +0100, Armin Rigo wrote:
>Hello Samuele,
>
>On Sat, Sep 13, 2003 at 04:18:51PM +0200, Samuele Pedroni wrote:
> > OTOH conflating 'with' and 'for' just for generators seems a rather ad-hoc
> > breaking of
> > orthoganility of the two, you could not write anymore code like this:
> >
> > g = gen()
> > for v in g:
> >   ... do something up to a point ...
> > ...
> > for v in g:
> >   ...
>
>I had thought about this. This occurs when you 'break' out of the first loop.
>I would say that NOT calling the __exit__() method in this specific case seems
>quite intuitive, the 'break' meaning 'just exit from the loop now without any
>further processing, skipping the 'else' part if present'.

Hmmm...  You realize this is also going to break the similarity between:

i = iter(something)
while 1:
     try:
         j=i.next()
     except StopIteration:
         break

and

for j in iter(something):
     pass


The former is already complex enough as a mental model.  I think it gets 
altogether too complex if one also has to consider the enter/leave 
issue.  This strikes me as an area like try/except vs. try/finally: it 
really should be a separate block, just for the sake of explicitness.  As 
much as it would be cool to have the automatic release, I think I'd rather use:

with i = iter(something):
     for j in i:
         ...

And make the resource management very visible.




More information about the Python-Dev mailing list