Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling coroutine from coroutine in python

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!

like image 397
oschlueter Avatar asked Dec 10 '25 23:12

oschlueter


1 Answers

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
like image 181
mitghi Avatar answered Dec 13 '25 13:12

mitghi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!