Trantor Liu
Trantor Liu

Reputation: 9126

Coroutines in python

I read the following code from a book, and have some questions about it.

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")

By using coroutine, no initial .next() is needed. My understanding is, if r = receiver(), then r = start, so when I call r.send(), it equals to start.send(), then I call .next() again, right? But the result is not what I expected.

Upvotes: 4

Views: 2598

Answers (1)

Tavis Rudd
Tavis Rudd

Reputation: 1156

Your problem isn't the coroutine. You're misunderstanding the function decorator. After r = receiver(), r is not start but g. Read up on function decoration and you'll understand what is going on.

Upvotes: 2

Related Questions