python yield from用法

yield from是python3.3之后新增的用法,主要是作为caller和genertor之间的通道来使用的。

先说从generator读,比如接受从yield出来的结构

def generator():
    for i in xrange(10):
        yield i

for i in (yield from (generator()))
    print i

还可以将结果透传,比如一个writer()处理的结果希望透传出去而本身里面有可能有正常data也可能有exception,就直接yield from writer透传出去

常用在AsyncIO时处理,比如

semaphore = asyncio.Semaphore(100)
with (yield from semaphore):
    # operations, 如果是爬虫可以response = yield from aiohttp.request(xxx)
    # body = yield from response.content.read()
    # yield from response.wait_for_close()

猜你喜欢

转载自blog.csdn.net/weixin_41571449/article/details/80158329