I’m learning about Coroutine but it work strange that I can’t understand…
Here’s the source
@coroutine
def printer():
tmp=(yield)
print tmp
def sender(coru):
coru.send("hello")
print "I'm sender"
if __name__=="__main__":
coru=printer()
sender(coru)
print "I'm master"
shows
hello
StopItertationError @ coru.send(“hello”)
while,
@coroutine
def printer():
while 1:
tmp=(yield)
print tmp
def sender(coru):
coru.send("hello")
print "I'm sender"
if __name__=="__main__":
coru=printer()
sender(coru)
print "I'm master"
shows
hello
I’m sender
I’m master
correctly.
So I’m wondering
-
why coroutine always work with the loops and why the first example rise error
-
I heared about ‘yield from’ syntax at version 3.3. Is that help to make the first one work?
-
I know every coroutine function work equivalently unlike the subroutines.
but then, I think, after the Printer function ends, the program should be terminated without returning to Sender.
but it does. doesn’t it means that sender superior to printer? what is the difference between subroutine and coroutine then.
thanks for reading and I really appreciate if you enlight me:)
When a generator (like
printer) ends, it raises a StopIteration exception.When Python executes
it jumps to
and assigns “hello” to
tmp. It then executes the next line:and then the generator ends, thus raising the
StopIterationexception.If, on the other hand, you do not allow
printerto end (by using awhile 1loop) then theStopIterationexception is never raised. Instead execution (inprinter) continues until the nextyieldexpression is reached:The
sendmethod returns the value of thatyieldexpression (in this case,None). At this point, Python has once again returned to thesenderfunction and next executesThe purpose of the
yield fromsyntax is to make it easier to refactor generators (intended to be used withsendandthrow) into subgenerators. See PEP380 and What’s New in Python3.It doesn’t change the StopIteration behavior.