__next__ and StopIteration

Chris Angelico rosuav at gmail.com
Mon Feb 9 19:54:22 EST 2015


On Tue, Feb 10, 2015 at 11:42 AM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> Also, *technically* iterators may be re-iterable. The docs say that
> iterators which fail to raise StopIteration forever once they are exhausted
> are "broken", but the docs do not forbid broken iterators. Consenting
> adults and all that. You might want an iterator with a reset() method. Even
> an outright broken iterator!
>
>     def __next__(self):
>         if random.random() < 0.1: raise StopIteration
>         return random.random()
>
> Why you would want one, I don't know, but if you have a hankering for such a
> beast, Python lets you do it.

Yes, it is allowed. But when you write code that's documented as being
"broken", you should expect annoying, subtle errors, maybe a long way
down the track. You know all those niggling problems you get when you
find some NaNs in a series of numbers, and suddenly things don't sort
stably and such? You'll hanker for those well-defined days. :)

ChrisA



More information about the Python-list mailing list