Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between send(None) and Next()

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
like image 958
KevB Avatar asked Feb 27 '15 00:02

KevB


1 Answers

What you are missing is that generators are a special case of iterators.

An iterator is anything which (correctly) implements the __iter__() and __next__() methods. The __iter__() method, in this case, is simply supposed to return the iterator itself. The __next__() method is called to implement next().

The key, however, is that __next__() takes no arguments (besides self). The .send() method is not part of the iteration protocol. In the general case, an iterator is not required to implement .send(). Indeed, if you call iter([]), you will get an object which lacks the method. Sending only works on true generators (functions written using the yield syntax). By contrast, next() works on any iterator.

like image 81
Kevin Avatar answered Oct 02 '22 16:10

Kevin