Coroutines in python

I read the following code from the book and have some questions about this.

def coroutine(func): def start(*args, **kwargs): g = func(*args, **kwargs) g.next() return g return start @coroutine def receiver(): print("Ready to receive") while True: n = (yield) print("Got %s" % n) r = receiver() r.send("hello, world") 

Using coroutine , the initial .next() not required. I understand if r = receiver() , then r = start , so when I call r.send() , it is equal to start.send() , then I call .next() again, right? But the result is not what I expected.

+4
source share
1 answer

Your problem is not in the coroutine. You misunderstand the function decorator. After r = receiver() r does not start, but g. Read the description of the function and you will understand what is happening.

+2
source

All Articles