It might be more clear if you look at it that way. Instead:
for i in mygen(): . . .
using:
gen_obj = mygen() for i in gen_obj: . . .
then you can see that mygen () is called only once, and it creates a new object, and it is this object that gets iterated. You could create two sequences in the same thread if you wanted:
gen1 = mygen() gen2 = mygen() print(gen1.__next__(), gen2.__next__(), gen1.__next__(), gen2.__next__())
This will print 0, 0, 1, 1.
You can access the same iterator from two threads, if you want, just save the generator object in the global:
global_gen = mygen()
Theme 1:
for i in global_gen: . . .
Theme 2:
for i in global_gen: . . .
This is likely to cause all kinds of chaos. :-)
source share