Clarke
Clarke

Reputation: 305

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.

Upvotes: 5

Views: 455

Answers (2)

Hashan Malawana
Hashan Malawana

Reputation: 363

Good question and I also used to follow this topic as I have never faced. What is found is , When a generator frame is (re)started(or as you said, stopping situation) as a result of a next() (or send() or throw()) call, one of three outcomes can occur:

  • A yield point is reached, and the yielded value is returned.
  • The frame is returned from; StopIteration is raised.
  • An exception is raised, which bubbles out.
  • In the latter two cases the frame is abandoned (and the generator object's gi_frame attribute is set to None). This changes to generators: when StopIteration is raised inside a generator, it is replaced with RuntimeError because of above reasons.

Please take a look for further details. thanks.

Upvotes: 0

Greg Schmit
Greg Schmit

Reputation: 4574

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.

Upvotes: 2

Related Questions