4

I am reading Python Essential Reference and I am unable to understand coroutine which receive and emits return values.

Here is what the author says - "A coroutine may simultaneously receive and emit return values using yield if values are supplied in the yield expression."

Here is an example that illustrates this:

def line_splitter(delimiter=None):
    print("Ready to split")
    result = None
    while True:
        line = (yield result)
        result = line.split(delimiter)

Further the author adds, In this case, we use the coroutine in the same way as before. However, now calls to send() also produce a result. For example:

>>> s = line_splitter(",")
>>> s.next()
Ready to split
>>> s.send("A,B,C")
['A', 'B', 'C' ]
>>> s.send("100,200,300")
['100', '200', '300']

I want to know how the above code works.

Thanks for any help.

  • http://stackoverflow.com/a/1756156/471899 – Alik Jul 22 '15 at 06:39
  • Hard to answer unless you can tell us which part you don't understand. Do you have a good understanding of the generator aspect? – John La Rooy Jul 22 '15 at 06:44
  • What I know about generators is that it uses yield keyword and produces a sequence of values used for iteration. I am not able to understand the working of above mentioned code. – user3379333 Jul 22 '15 at 06:50

1 Answers1

4

Let's see what the calling code does, line by line:

  • s = line_splitter(",") This line just initializes the generator, without executing any of the code within it.
  • s.next() This executes the code up to and including the next yield statement, printing the line and yielding None. The assignment result = ..., however, is not executed yet.
  • s.send("A,B,C") This sets the "value" of yield within the generator to "A,B,C" and executes the code up to and including the next yield, thus assigning it to result.

In a sense, the yield keyword can be used for both, getting values out of the generator (using next) and at the same time injecting values into the generator (using send).

For a more in-depth explanation, you might also have a look at this answer.

Community
  • 1
  • 1
tobias_k
  • 74,298
  • 11
  • 102
  • 155