Why are "broken iterators" broken?

Miles semanticist at gmail.com
Mon Sep 22 07:30:36 CEST 2008


On Sun, Sep 21, 2008 at 11:13 AM, Steven D'Aprano
<steve at remove-this-cybersource.com.au> wrote:
> According to the Python docs, once an iterator raises StopIteration, it
> should continue to raise StopIteration forever. Iterators that fail to
> behave in this fashion are deemed to be "broken":
>
> http://docs.python.org/lib/typeiter.html
>
> I don't understand the reasoning behind this. As I understand it, an
> iterator is something like a stream. There's no constraint that once a
> stream is empty it must remain empty forever.
>
> Can somebody explain why "broken iterators" are broken?

It's not a terribly onerous restriction.  If you're iterating with a
for-loop, you can make the iterable return a new iterator object when
the old one is exhausted, and if the intent is for the next()-method
to be called directly, you don't have to conform to the iterator
protocol.

Strictly speaking, file objects are broken iterators:

Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:16)
>>> f = open('foo')
>>> it = iter(f)
>>> it.next()
'hi\n'
>>> it.next()
'bye\n'
>>> it.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> f.seek(0)
>>> it.next()
'hi\n'

-Miles



More information about the Python-list mailing list