What’s the purpose of “send” function on Python generators?

Can someone give me an example of why the “send” function associated with Python generator function exists? I fully understand the yield function. However, the send function is confusing to me. The documentation on this method is convoluted:

generator.send(value)

Resumes the execution and “sends” a value into the generator function. The value argument becomes the result of the current yield expression. The send() method returns the next value yielded by the generator, or raises StopIteration if the generator exits without yielding another value.

What does that mean? I thought value was the input to the function? The phrase “The send() method returns the next value yielded by the generator” seems to be also the exact purpose of the yield function; yield returns the next value yielded by the generator…

Can someone give me an example of a generator utilizing send that accomplishes something yield cannot?

9 Answers
9

Leave a Comment