On Mon, 27 Jul 2009 02:02:19 -0400, Terry Reedy wrote: > Steven D'Aprano wrote: >> On Sun, 26 Jul 2009 20:10:00 -0400, Terry Reedy wrote: >> >>> Michal Kwiatkowski wrote: >>> >>>> The thing is I don't need the next item. I need to know if the >>>> generator has stopped without invoking it. >>> Write a one-ahead iterator class, which I have posted before, that >>> sets .exhausted to True when next fails. >> >> >> And hope that the generator doesn't have side-effects... > > If run to exhastion, the same number of side-effects happen. The only > difference is that they each happen once step happpen sooner. For > reading a file that is irrelevant. Much else, and the iterator is not > just an iterator.
I believe the OP specifically said he needs to detect whether or not an iterator is exhausted, without running it to exhaustion, so you shouldn't assume that the generator has been exhausted. When it comes to side-effects, timing matters. For example, a generator which cleans up after it has run (deleting temporary files, closing sockets, etc.) will leave the environment in a different state if run to exhaustion than just before exhaustion. Even if you store the final result in a one-ahead class, you haven't saved the environment, and that may be significant. (Of course, it's possible that it isn't significant. Not all differences make a difference.) The best advice is, try to avoid side-effects, especially in generators. -- Steven -- http://mail.python.org/mailman/listinfo/python-list