Reputation: 16940
When i was googling for python yield
i found something interesting and I never knew before i.e we can pass value to yield to change the next() value. I hope some of the new pythonist might now aware of this and I am not sure how it works too. So, If any body could explain how it works and how the behavior changes when i send a new index to yield using send()
.
Here is my snippets :
def print_me (count):
i = 0
while i < count:
val = (yield i)
if val is not None:
i = val
else:
i += 1
gen = print_me(10)
for i in gen:
if i == 5:
gen.send(8)
else:
print i
Here is my output:
0
1
2
3
4
9
Upvotes: 3
Views: 2551
Reputation: 310089
Your test code is pretty instructive actually. What happens in a generator function like this is that whenever you call next
on the generator, code gets executed until it hits a yield
statement. The value is yielded and then execution in the generator "pauses". If you .send
some data to the generator, that value is returned from yield
. If you don't .send
anything, yield
returns None
.
So in your code, when you .send(8)
, then it sets val = 8
inside your generator (val = yield i
). since val is not None
, i
is set to 8
. .send
actually executes until the next yield statement (returning that value -- 8
). Then things resume as normal (the next number to be yielded is 9
).
Upvotes: 4