(My reply didn't seem to have reached python-dev... second try.)
On Tue, Aug 26, 2003 at 01:50:52PM -0700, Guido van Rossum wrote:
Another comment on Samuele's PEP: It is sort of sad that the *user* of a generator has to know that the generator's close() must be called. Normally, the beauty of using a try/finally for cleanup is that your callers don't need to know about it. But I see no way around this.
What about letting the 'for' handle this? It's the most common way generators are used. When a 'for' loop on a generator-iterator finishes it would call the close() method of the iterator, which on generators would (say) simulate a return from the latest 'yield'.
Well, close() might not be such a good name because it would probably break exsiting code (e.g. closing files unexpectedly), but __exit__() might do. In other words we could import some of the proposed functionality of the 'with' keyword (PEP 310) into 'for'. I think it makes sense because 'for' is already defined in term of implicit calls to next(), the only method of iterators; so if a second method is added, 'for' can be taught about it too.