Why exhausted generators raise StopIteration more than once?
<p>Why is it that when an exhausted generator is called several times, <code>StopIteration</code> is raised every time, rather than just on the first attempt? Aren't subsequent calls meaningless, and indicate a likely bug in the caller's code?</p>

<pre><code>def gen_func():
    yield 1
    yield 2
gen = gen_func()
next(gen)
next(gen)
next(gen) # StopIteration as expected
next(gen) # why StopIteration and not something to warn me that I'm doing something wrong
</code></pre>

<p>This also results in this behavior when someone accidentally uses an expired generator:</p>

<pre><code>def do_work(gen):
    for x in gen:
        # do stuff with x
        pass

    # here I forgot that I already used up gen
    # so the loop does nothing without raising any exception or warning
    for x in gen:
        # do stuff with x
        pass

def gen_func():
    yield 1
    yield 2

gen = gen_func()
do_work(gen)
</code></pre>

<p>If second and later attempts to call an exhausted generator raised a different exception, it would have been easier to catch this type of bugs.</p>

<p>Perhaps there's an important use case for calling exhausted generators multiple times and getting <code>StopIteration</code>?</p>

<p>It is a part of the iteration protocol:</p>

<blockquote>
  <p>Once an iteratorâs <code>__next__()</code> method raises StopIteration, it must
  continue to do so on subsequent calls. Implementations that do not
  obey this property are deemed broken.</p>
</blockquote>

<p>Source: <a href="https://docs.python.org/3/library/stdtypes.html#iterator-types" rel="nofollow">https://docs.python.org/3/library/stdtypes.html#iterator-types</a></p>

python python-3.x generator