In your example the print_forever
is instanciated once, then passed to the limit_gen
one. After being called once, the first one has yield its one value and reach its own end, raising a StopIteration exception.
There are various ways to make it work, you could for example instanciate a new generator at each iteration:
def print_forever(v):
yield v
def limit_gen(gen, v, n):
for _ in range(n):
yield next(gen(v))
for v in limit_gen(print_forever, 2, 5):
print(v)
Another option is to make a really infinite generator:
def print_forever(v):
while 1:
yield v
def limit_gen(gen, n):
for _ in range(n):
yield next(gen)
for v in limit_gen(print_forever(2), 5):
print(v)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…