Why do obsolete generators raise StopIteration more than once?

Why, when a generated generator is called several times, StopIterationoccurs every time, and not just the first attempt? Are subsequent calls pointless and indicate a likely error in the caller’s 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

This also leads to this behavior when someone accidentally uses an expired generator:

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)

If a second and subsequent attempt to call an obsolete generator raised another exception, it would be easier to catch this type of error.

Perhaps there is an important precedent for calling outdated generators and receiving at the same time StopIteration?

+4
source share
2

, StopIteration?

, , . itertools , :

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)
+2
+4

Source: https://habr.com/ru/post/1655367/


All Articles