This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author steven.daprano
Recipients steven.daprano, yoonghm
Date 2019-01-12.06:28:27
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1547274507.23.0.744247659089.issue35725@roundup.psfhosted.org>
In-reply-to
Content
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")
History
Date User Action Args
2019-01-12 06:28:28steven.dapranosetrecipients: + steven.daprano, yoonghm
2019-01-12 06:28:27steven.dapranosetmessageid: <1547274507.23.0.744247659089.issue35725@roundup.psfhosted.org>
2019-01-12 06:28:27steven.dapranolinkissue35725 messages
2019-01-12 06:28:27steven.dapranocreate