I was experimenting with generators in python 3 and wrote this rather contrived generator :
def send_gen():
print(" send_gen(): will yield 1")
x = yield 1
print(" send_gen(): sent in '{}'".format(x))
# yield # causes StopIteration when left out
gen = send_gen()
print("yielded {}".format(gen.__next__()))
print("running gen.send()")
gen.send("a string")
Output:
send_gen(): will yield 1
yielded 1
running gen.send()
send_gen(): sent in 'a string'
Traceback (most recent call last):
File "gen_test.py", line 12, in <module>
gen.send("a string")
StopIteration
So gen.__next__()
reaches the line x = yield 1
and yields 1. I thought x
would be assigned to None
, then gen.send()
would look for the next yield
statement because x = yield 1
is "used", then get a StopIteration
.
Instead, what seems to have happened is that x
gets sent "a string", which is printed, then then python attempts to look for the next yield
and gets a StopIteration
.
So i try this:
def send_gen():
x = yield 1
print(" send_gen(): sent in '{}'".format(x))
gen = send_gen()
print("yielded : {}".format(gen.send(None)))
Output :
yielded : 1
But now there's no error. send()
doesn't appear to have tried to look for the next yield
statement after assigning x
to None
.
Why is the behaviour slightly different ? Does this have to do with how I started the generators ?
x = ...
explanations helped a lot. Thanks ! – Incoherent