4

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.

1
  • What result were you expecting? Commented Oct 26, 2011 at 3:10

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Rudd. Let me explain this with my understanding again. The call r = receiver() is equals to r = coroutune(receiver)(), which becomes r = start(), thus r finally is g. Is that right?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.