__next__ and StopIteration

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Feb 9 20:11:54 EST 2015


Chris Angelico wrote:

> 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.

Well, that depends, don't it?

If you're writing library code, you need to be much more careful and
thoughtful about both your API and implementation.

But if you're writing something quick and dirty for a one-off script, even a
script that is going to be used in perpetuity, you can afford a lot more
sloppiness. Better something sloppy that works today than something perfect
next year. Say my script just outputs a bunch of random numbers, one per
line, and I pipe the output to a file in the shell:

mkrnd.py > the_numbers.txt

Am I really going to care if the iterator used to generate those random
numbers is technically "broken"? Probably not. And if I do, some time in
the distant future, oh well, I'll "fix" it then.



-- 
Steven




More information about the Python-list mailing list