Steven D'Aprano <steve+pyt...@pearwood.info> added the comment:

This is not a bug, it is standard behaviour for all iterators, not just 
generators.

For loops work by calling next() on the iterator object, if you call next() on 
the same object inside the loop, that has the effect of advancing the for loop.

You say:

> I noticed that the generator function will execute whenever it is in the 
> for...in loop.

but that's actually incorrect, as the generator FUNCTION f() is not inside the 
for loop. Each time you call the generator function f() you get a separate, 
independent generator object. In this case, you only call f() once, so you only 
have one generator object `gen`. Each time next(gen) is called, it advances to 
the next yield. It doesn't matter whether you call it manually, or the 
interpreter calls it for you using the for loop.

Try these two examples and compare their difference:

gen = f()
for x in gen:
    print(x, "outer loop")
    for y in gen:
        print(y, "inner loop")


versus:

for x in f():
    print(x, "outer loop")
    for y in f():
        print(y, "inner loop")

----------
nosy: +steven.daprano
resolution:  -> not a bug
stage:  -> resolved
status: open -> closed

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue35725>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to