[Python-ideas] with expression

Chris Angelico rosuav at gmail.com
Fri Feb 21 05:47:17 CET 2014


On Fri, Feb 21, 2014 at 9:01 AM, Andrew Barnert <abarnert at yahoo.com> wrote:
> No it's not. The file will be closed as soon as the iterator is fully consumed, even if it's not deleted until much later.
>
> Of course it does mean that if you abandon the iterator in the middle you're leaking the generator and therefore the file until deletion. But there are many use cases where that doesn't come up.

ISTM that could be dealt with by explicitly ending the generator.

    with open('name') as f:
        for line in f:
           if (yield line.split()): break

Then you just send it a nonzero value and there you are, out of your
difficulty at once!

ChrisA


More information about the Python-ideas mailing list