user3379333
user3379333

Reputation: 43

Python Coroutines that receive and emits return values

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.

Upvotes: 4

Views: 908

Answers (1)

tobias_k
tobias_k

Reputation: 82899

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.

Upvotes: 5

Related Questions