<div dir="ltr">Ohhh, sorry, you want __iterclose__ to happen when iteration is terminated by a break statement as well? Okay, I understand, and that's fair.<div><br></div><div>However, I would rather that people be explicit about when they're iterating (use the iteration protocol) and when they're managing a resource (use a context manager). Trying to figure out where the context manager should go automatically (which is what it sounds like the proposal amounts to) is too difficult to get right, and when you get it wrong you close too early, and then what's the user supposed to do? Suppress the early close with an even more convoluted notation?</div><div><br></div><div>If there is a problem with people iterating over things without a generator, my suggestion is to force them to use the generator. For example, don't make your object iterable: make the value yielded by the context manager iterable.</div><div><br></div><div>Best,</div><div><br></div><div>Neil</div><div><br></div><div>(On preview, Re: Chris Angelico's refactoring of my code, nice!!)</div><div><br>On Wednesday, October 19, 2016 at 4:14:32 PM UTC-4, Neil Girdhar wrote:<blockquote class="gmail_quote" style="margin: 0;margin-left: 0.8ex;border-left: 1px #ccc solid;padding-left: 1ex;"><div dir="ltr"><br><br><div class="gmail_quote"><div dir="ltr">On Wed, Oct 19, 2016 at 2:11 PM Nathaniel Smith <<a href="mailto:njs@pobox.com" target="_blank" rel="nofollow" onmousedown="this.href='mailto:njs@pobox.com';return true;" onclick="this.href='mailto:njs@pobox.com';return true;">njs@pobox.com</a>> wrote:<br></div><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">On Wed, Oct 19, 2016 at 10:08 AM, Neil Girdhar <<a href="mailto:mistersheik@gmail.com" target="_blank" rel="nofollow" onmousedown="this.href='mailto:mistersheik@gmail.com';return true;" onclick="this.href='mailto:mistersheik@gmail.com';return true;">mistersheik@gmail.com</a>> wrote:<br>
><br>
><br>
> On Wed, Oct 19, 2016 at 11:08 AM Todd <<a href="mailto:toddrjen@gmail.com" target="_blank" rel="nofollow" onmousedown="this.href='mailto:toddrjen@gmail.com';return true;" onclick="this.href='mailto:toddrjen@gmail.com';return true;">toddrjen@gmail.com</a>> wrote:<br>
>><br>
>> On Wed, Oct 19, 2016 at 3:38 AM, Neil Girdhar <<a href="mailto:mistersheik@gmail.com" target="_blank" rel="nofollow" onmousedown="this.href='mailto:mistersheik@gmail.com';return true;" onclick="this.href='mailto:mistersheik@gmail.com';return true;">mistersheik@gmail.com</a>><br>
>> wrote:<br>
>>><br>
>>> This is a very interesting proposal. I just wanted to share something I<br>
>>> found in my quick search:<br>
>>><br>
>>><br>
>>> <a href="http://stackoverflow.com/questions/14797930/python-custom-iterator-close-a-file-on-stopiteration" rel="nofollow" target="_blank" onmousedown="this.href='http://www.google.com/url?q\x3dhttp%3A%2F%2Fstackoverflow.com%2Fquestions%2F14797930%2Fpython-custom-iterator-close-a-file-on-stopiteration\x26sa\x3dD\x26sntz\x3d1\x26usg\x3dAFQjCNE4-oQdmEKCVGXLCQPJlJfrpZ--zA';return true;" onclick="this.href='http://www.google.com/url?q\x3dhttp%3A%2F%2Fstackoverflow.com%2Fquestions%2F14797930%2Fpython-custom-iterator-close-a-file-on-stopiteration\x26sa\x3dD\x26sntz\x3d1\x26usg\x3dAFQjCNE4-oQdmEKCVGXLCQPJlJfrpZ--zA';return true;">http://stackoverflow.com/<wbr>questions/14797930/python-<wbr>custom-iterator-close-a-file-<wbr>on-stopiteration</a><br>
>>><br>
>>> Could you explain why the accepted answer there doesn't address this<br>
>>> issue?<br>
>>><br>
>>> class Parse(object):<br>
>>> """A generator that iterates through a file"""<br>
>>> def __init__(self, path):<br>
>>> self.path = path<br>
>>><br>
>>> def __iter__(self):<br>
>>> with open(self.path) as f:<br>
>>> yield from f<br>
<br>
BTW it may make this easier to read if we notice that it's essentially<br>
a verbose way of writing:<br>
<br>
def parse(path):<br>
with open(path) as f:<br>
yield from f<br>
<br>
>><br>
>> I think the difference is that this new approach guarantees cleanup the<br>
>> exact moment the loop ends, no matter how it ends.<br>
>><br>
>> If I understand correctly, your approach will do cleanup when the loop<br>
>> ends only if the iterator is exhausted. But if someone zips it with a<br>
>> shorter iterator, uses itertools.islice or something similar, breaks the<br>
>> loop, returns inside the loop, or in some other way ends the loop before the<br>
>> iterator is exhausted, the cleanup won't happen when the iterator is garbage<br>
>> collected. And for non-reference-counting python implementations, when this<br>
>> happens is completely unpredictable.<br>
>><br>
>> --<br>
><br>
><br>
> I don't see that. The "cleanup" will happen when collection is interrupted<br>
> by an exception. This has nothing to do with garbage collection either<br>
> since the cleanup happens deterministically when the block is ended. If<br>
> this is the only example, then I would say this behavior is already provided<br>
> and does not need to be added.<br>
<br>
I think there might be a misunderstanding here. Consider code like<br>
this, that breaks out from the middle of the for loop:<br>
<br>
def use_that_generator():<br>
for line in parse(...):<br>
if found_the_line_we_want(line):<br>
break<br>
# -- mark --<br>
do_something_with_that_line(<wbr>line)<br>
<br>
With current Python, what will happen is that when we reach the marked<br>
line, then the for loop has finished and will drop its reference to<br>
the generator object. At this point, the garbage collector comes into<br>
play. On CPython, with its reference counting collector, the garbage<br>
collector will immediately collect the generator object, and then the<br>
generator object's __del__ method will restart 'parse' by having the<br>
last 'yield' raise a GeneratorExit, and *that* exception will trigger<br>
the 'with' block's cleanup. But in order to get there, we're<br>
absolutely depending on the garbage collector to inject that<br>
GeneratorExit. And on an implementation like PyPy that doesn't use<br>
reference counting, the generator object will become collect*ible* at<br>
the marked line, but might not actually be collect*ed* for an<br>
arbitrarily long time afterwards. And until it's collected, the file<br>
will remain open. 'with' blocks guarantee that the resources they hold<br>
will be cleaned up promptly when the enclosing stack frame gets<br>
cleaned up, but for a 'with' block inside a generator then you still<br>
need something to guarantee that the enclosing stack frame gets<br>
cleaned up promptly!<br></blockquote><div><br></div><div>Yes, I understand that. Maybe this is clearer. This class adds an iterclose to any iterator so that when iteration ends, iterclose is automatically called:</div><div><br></div><div><div>def my_iterclose():</div><div> print("Closing!")</div><div><br></div><div><br></div><div>class AddIterclose:</div><div><br></div><div> def __init__(self, iterable, iterclose):</div><div> self.iterable = iterable</div><div> self.iterclose = iterclose</div><div><br></div><div> def __iter__(self):</div><div> try:</div><div> for x in self.iterable:</div><div> yield x</div><div> finally:</div><div> self.iterclose()</div><div><br></div><div><br></div><div>try:</div><div> for x in AddIterclose(range(10), my_iterclose):</div><div> print(x)</div><div> if x == 5:</div><div> raise ValueError</div><div>except:</div><div> pass</div></div><div><br></div><div> </div><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
<br>
This proposal is about providing that thing -- with __(a)iterclose__,<br>
the end of the for loop immediately closes the generator object, so<br>
the garbage collector doesn't need to get involved.<br>
<br>
Essentially the same thing happens if we replace the 'break' with a<br>
'raise'. Though with exceptions, things can actually get even messier,<br>
even on CPython. Here's a similar example except that (a) it exits<br>
early due to an exception (which then gets caught elsewhere), and (b)<br>
the invocation of the generator function ended up being kind of long,<br>
so I split the for loop into two lines with a temporary variable:<br>
<br>
def use_that_generator2():<br>
it = parse("/a/really/really/<wbr>really/really/really/really/<wbr>really/long/path")<br>
for line in it:<br>
if not valid_format(line):<br>
raise ValueError()<br>
<br>
def catch_the_exception():<br>
try:<br>
use_that_generator2()<br>
except ValueError:<br>
# -- mark --<br>
...<br>
<br>
Here the ValueError() is raised from use_that_generator2(), and then<br>
caught in catch_the_exception(). At the marked line,<br>
use_that_generator2's stack frame is still pinned in memory by the<br>
exception's traceback. And that means that all the local variables are<br>
also pinned in memory, including our temporary 'it'. Which means that<br>
parse's stack frame is also pinned in memory, and the file is not<br>
closed.<br>
<br>
With the __(a)iterclose__ proposal, when the exception is thrown then<br>
the 'for' loop in use_that_generator2() immediately closes the<br>
generator object, which in turn triggers parse's 'with' block, and<br>
that closes the file handle. And then after the file handle is closed,<br>
the exception continues propagating. So at the marked line, it's still<br>
the case that 'it' will be pinned in memory, but now 'it' is a closed<br>
generator object that has already relinquished its resources.<br>
<br>
-n<br>
<br>
--<br>
Nathaniel J. Smith -- <a href="https://vorpus.org" rel="nofollow" target="_blank" onmousedown="this.href='https://www.google.com/url?q\x3dhttps%3A%2F%2Fvorpus.org\x26sa\x3dD\x26sntz\x3d1\x26usg\x3dAFQjCNGu9BH-CNkjUnoU8qy5kxnhJP302A';return true;" onclick="this.href='https://www.google.com/url?q\x3dhttps%3A%2F%2Fvorpus.org\x26sa\x3dD\x26sntz\x3d1\x26usg\x3dAFQjCNGu9BH-CNkjUnoU8qy5kxnhJP302A';return true;">https://vorpus.org</a><br>
</blockquote></div></div>
</blockquote></div></div>