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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With