3

I came across this issue today and I'm not quite certain why it works like this:

def outside():
    print 'before'
    inside()
    print 'after'
    yield 'World'

def inside():
    print 'inside'
    yield 'Hello'

for n in outside():
    print n

(Naive) expectation of output:

before
inside
Hello
after
World

Actual output:

before
after
World

Is it not possible to call a coroutine from inside a coroutine? The articles I read on coroutines and yield didn't elaborate on this issue and I'm quite lost here. Could anyone shed some light on this behaviour please? Thanks in advance!

1
  • 2
    Well what you have there is two generator functions not coroutine. Commented Jul 12, 2016 at 12:09

1 Answer 1

3

It is totally possible. when you call inside() it creates a coroutine. In order to yield the result, you need to initialize the coroutine and yield from it as follows:

def outside():
     print 'before'
     for i in inside():
         yield i
     print 'after'
     yield 'World'

and the result would be as expected:

before
inside
Hello
after
World
Sign up to request clarification or add additional context in comments.

2 Comments

the for loop in @purrogrammer example is important. A generator is an iterator. You need to call the __next__() method which is done by the for loop. Note that in your example @oschlueter, you invoked your inside function without calling it as an iterator. So in fact, it was never really invoked.
This is the right answer. Mainly because you misunderstood the idea of co-routines.. at each yield statement the function gives up control to the caller. In the original case, the inside call() was giving back execution control to the outside() function, but that didn't print explicitly. However the standard call to the file which was the caller of outside() prints strings to stdout by default. That's why this difference.

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.