Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if we stop iteration before a generator object raises a 'StopIteration' exception

I have a generator object that checks a certain condition on a list. This program works fine for all my cases.

But I just want to clarify some key points.

In my program Whenever the generator yield the values 'No' or 'Done' the controlling iteration stops and calls the generator with another argument.

This may be a silly question, anyway that is, whenever the generator object is yielded and we stops calling next to it, does that object is settled for garbage collecting? Or is that yielded object is being settled to garbage collecting when we call that generator again with another argument.

Please clarify this to me what happens to a generator object if we stops calling next() on it before it raise a StopIteration exception. What happens to the persevered execution points and variables of the current generator object, when we again call the generator with a new argument.

like image 877
Clarke Avatar asked Oct 27 '22 22:10

Clarke


1 Answers

I debated making this a comment because I'm not an expert on the GC implementation details in Python, but decided on an answer since it seems like it might be helpful.

I think it only gets garbage collected when you lose all references to it, but it shouldn't matter, as generators are usually used to avoid storing stuff in memory, so they aren't usually very large. I think it's fine to stop using it before it hits StopIteration. In fact, many generators never call StopIteration (e.g., if they are enumerating some infinite series), so it's expected that you stop calling next on it before hitting the "end" in many cases.

like image 189
Greg Schmit Avatar answered Oct 30 '22 00:10

Greg Schmit