By redefining the yield statement to be an expression in PEP 342-- Coroutines via Enhanced Generators powerful new functionality was added to Python. David Beasley has an excellent presentation on Python coroutines A Curious Course on Coroutines and Concurrency.
As the PEP states, A yield expression's value is None whenever the generator is resumed by a normal next() call. To instantiate the generator either next() or send(None) must be called (i.e. cannot send non-None value initially).
Is there any advantage in calling next() vs send(None)? next() is a Built_in function, so perhaps that's a factor, but there doesn't seem to be any other differences. I'm somewhat surprised, it would seem more Pythonic to add an optional variable to next than add a new function that does the same thing. Am I missing something?
Here is a simple coroutine to keep a running total of numbers entered, by sending them to the coroutine.
import numbers
def running_sum() :
g_in = 0
g_out = 0
while g_in is not None :
g_in = (yield g_out)
if isinstance(g_in, numbers.Number) :
g_out += g_in
print 'in_val =',g_in,'sum =',g_out