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)
next(gen)
This also leads to this behavior when someone accidentally uses an expired generator:
def do_work(gen):
for x in gen:
pass
for x in gen:
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?
source
share