coroutine and yield

来源:互联网 发布:linux expect root 编辑:程序博客网 时间:2024/04/29 07:39
Inside a function, the yield statement can also be used as an expression that appears on the right side of an assignment operator.

A function that uses yield in this manner is known as a coroutine, and it executes in response to values being sent to it.

For example:

def receiver():
    print("Ready to receive")
    while True:
        n = (yield)
        print("Got %s" % n)

>>> r = receiver()
>>> r.next() # Advance to first yield (r._ _next_ _() in Python 3)
Ready to receive
>>> r.send(1)
Got 1
>>> r.send(2)
Got 2
>>> r.send("Hello")
Got Hello
>>>

In this example, the initial call to next() is necessary so that the coroutine executes statements leading to the first yield expression.


A coroutine will typically run indefinitely unless it is explicitly shut down or it exits on its own.To close the stream of input values, use the close() method like this:
>>> r.close()
>>> r.send(4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration



原创粉丝点击