Distinguishing active generators from exhausted ones

Hendrik van Rooyen hendrik at microcorp.co.za
Sun Jul 26 03:48:49 EDT 2009

On Saturday 25 July 2009 20:30:54 Michal Kwiatkowski wrote:
> Hi,
> Is there a way to tell if a generator has been exhausted using pure
> Python code? I've looked at CPython sources and it seems that
> something like "active"/"exhausted" attribute on genobject is missing
> from the API. For the time being I am using a simple C extension to
> look at f_stacktop pointer of the generator frame, which seems to
> differentiate active generators from exhausted ones. See
> http://bazaar.launchpad.net/~ruby/pythoscope/support-python2.3/annotate/286
>/pythoscope/_util.c#L16 for complete source code.
> I may be missing something obvious here. Is there a better way to tell
> if a given generator object is still active or not?

Is there a reason why you cannot just call the next method and handle
the StopIteration when it happens?

- Hendrik

More information about the Python-list mailing list