On Fri, Sep 30, 2016 at 2:36 AM, MRAB <pyt...@mrabarnett.plus.com> wrote: > On 2016-09-29 16:56, Steve D'Aprano wrote: >> >> On Thu, 29 Sep 2016 09:53 pm, MRAB wrote: >> >>> What if an _exhausted_ iterator was falsey? >> >> >> >> The problem is that in general you can't tell if an iterator is exhausted >> until you attempt to advance it. So even if bool(iterator) returns True, >> the call to next() may raise StopIteration: >> > [snip] > > By "exhausted" I meant "has previously raised StopIteration".
I'm not sure how useful that'd be, especially given that some iterators actually violate the normal rule of "once you raise, you raise thereafter". But it's not hard to wrap. class Iterator: def __init__(self, it): self.iter = iter(it) self.exhausted = False def __iter__(self): return self def __next__(self): try: return next(self.iter) except StopIteration: # or just 'except:'? self.exhausted = True raise def __bool__(self): return self.exhausted Then you have the edge cases. If next() raises something other than StopIteration, does that mark the iterator as exhausted? Should the exhausted flag be cleared if a naughty iterator yields a value after having StoppedIteration? (Also, you'd probably want to have some code in here to detect if it's working with a generator, and if so, pass send/throw down the line too. Omitted for simplicity.) ChrisA -- https://mail.python.org/mailman/listinfo/python-list