Reputation: 2698
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!
Upvotes: 3
Views: 1101
Reputation: 919
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
Upvotes: 3