__next__ and StopIteration

Chris Kaynor ckaynor at zindagigames.com
Mon Feb 9 19:59:17 EST 2015


On Mon, Feb 9, 2015 at 4:42 PM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> so that's an excellent sign that doing so is best practice, but it should
> not be seen as *required*. After all, perhaps you have good reason for
> wanting your iterable class to only be iterated over once.

In fact, there is one in the stdlib, the "file" object, which has a
__iter__ which returns self. The code below shows this,

There are a number of good reasons: perhaps there is no good way to
reset the iterator or there is outside state that has to be managed.
I'm also sure there are other reasons I cannot think of right now.

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

The "file" object is also an example of this. It is technically a
broken iterator according to the docs:

Python 3.4.2 (v3.4.2:ab2c023a9432, Oct  6 2014, 22:15:05) [MSC v.1600
32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open("d:/test.txt")
>>> iter(f) is f
True
>>> for l in f:
...     print(l)
...
line 1

line 2

line 3

>>> for l in f:
...     print(l)
...
>>> f.seek(0)
0
>>> for l in f:
...     print(l)
...
line 1

line 2

line 3

>>> next(f)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> f.seek(0)
0
>>> next(f) # This should throw StopIteration as it has previously thrown StopIteration.
'line 1\n'
>>>



Chris



More information about the Python-list mailing list