I experimented with generators in python 3 and wrote this pretty far-fetched generator:
def send_gen():
print(" send_gen(): will yield 1")
x = yield 1
print(" send_gen(): sent in '{}'".format(x))
gen = send_gen()
print("yielded {}".format(gen.__next__()))
print("running gen.send()")
gen.send("a string")
Conclusion:
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, it gen.__next__()reaches the line x = yield 1and gives 1. I thought it xwould be assigned None, then it gen.send()will search for the next statement yield, because x = yield 1"" is used, then get StopIteration.
Instead, it seems that what happened is that a x"string" is sent, which is printed, and then python tries to find the next one yieldand receives 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 is no mistake. send()doesn't seem to be trying to find the next statement yieldafter assignment xto None.
? , ?