[Python-ideas] with expression

Andrew Barnert abarnert at yahoo.com
Fri Feb 21 07:20:52 CET 2014


On Feb 20, 2014, at 20:47, Chris Angelico <rosuav at gmail.com> wrote:

> 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!

Good point!

But there are still plenty of cases where you're feeding an iterator to some function that may just abandon it mid-way through. In that case, you cannot use the with-iter trick. Only when you know the consumer will consume the whole thing--or, as you point out, when you can make the consumer cooperate with you (which is easy if you're writing the consumer code, not so much otherwise)--is it helpful.

I have a lot of scripts that use this; it's just important to know the limitations on it.


More information about the Python-ideas mailing list