[Python-Dev] pre-PEP: Resource-Release Support for
Generators
Samuele Pedroni
pedronis at bluewin.ch
Sat Sep 13 10:18:51 EDT 2003
At 14:46 13.09.2003 +0100, Armin Rigo wrote:
>Hello,
>
>(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.
I expect generators to grow also a __exit__ if they grow a close and PEP
310 is accepted,
this idiom will then be common
with g = gen()
for v in g:
...
but it will be common for files and file-like too. It can be reasonable to
discuss
whether we want a special syntax then that conflates 'with' and 'for' behavior.
But we can experiment a while before seeing whether writing the idiom is
unbearably
tedious ;).
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:
...
now this is rare but still breaking orthoganility of primitives is
something I would think twice about.
regards.
More information about the Python-Dev
mailing list