[Python-Dev] Rationale behind lazy map/filter (original) (raw)

Chris Angelico rosuav at gmail.com
Tue Oct 13 12:36:20 EDT 2015


On Wed, Oct 14, 2015 at 3:08 AM, Random832 <random832 at fastmail.com> wrote:

If you are writing code that tries to resume iterating after the iterator has been exhausted, I have to ask: why?

A well-behaved iterator is supposed to continue raising StopIteration forever once it's been exhausted. I don't know how much code actually depends on this, but it wouldn't be hard to make a wrapper that raises a different exception instead:

class iter: _orig_iter = iter def init(self, thing): self.iter = self._orig_iter(thing) self.exhausted = False def iter(self): return self def next(self): if self.exhausted: raise RuntimeError("Already exhausted") try: return next(self.iter) except StopIteration: self.exhausted = True raise

Play with that, and see where RuntimeErrors start coming up. I suspect they'll be rare, but they will happen.

ChrisA



More information about the Python-Dev mailing list