python中的协程的理解
2019-10-03 本文已影响0人
北雁南飞_8854
yield from x
对x做的第一件事情就是调用iter(x),从中获取一个迭代器(iterator),这意味着x可以是任何可迭代(iterable)的对象。
- yield from可用于简化for循环中的yield表达式
>>> def gen():
... for c in 'AB':
... yield c
... for i in range(1, 3):
... yield i
...
>>> list(gen())
['A', 'B', 1, 2]
可简化为:
>>> def gen():
... yield from 'AB'
... yield from range(1, 3)
...
>>> list(gen())
['A', 'B', 1, 2]
另外一个例子:
>>> def chain(*iterables):
... for it in iterables:
... yield from it
...
>>> s = 'ABC'
>>> t = tuple(range(3))
>>> list(chain(s, t))
['A', 'B', 'C', 0, 1, 2]
Chaining Coroutines
1. Coroutines(async def 和await)
python 3.5引入了async def表示一个函数是一个coroutine对象,和await结合使用。
一个coroutine能启动另一个coroutine、并等待它的结果。一个应用场景是:将一个task拆分为几个可用的组件、并按顺序执行。
例子:
#!/usr/bin/env python3
# asyncio_coroutine_chain.py
import asyncio
async def outer():
print('in outer')
print('waiting for result1')
result1 = await phase1()
print('waiting for result2')
result2 = await phase2(result1)
return result1, result2
async def phase1():
print('in phase1')
return 'result1'
async def phase2(arg):
print('in phase2')
return 'result2 derived from {}'.format(arg)
if __name__ == '__main__':
event_loop = asyncio.get_event_loop()
try:
return_value = event_loop.run_until_complete(outer())
print('return value: {!r}'.format(return_value))
finally:
event_loop.close()
输出:
in outer
waiting for result1
in phase1
waiting for result2
in phase2
return value: ('result1', 'result2 derived from result1')
2. generator functions(@asyncio.coroutine和yield from)
python3.5以前的版本使用generator functions、并加上asyncio.coroutine() decorator、和yield from一起可以实现同样的效果。
#!/usr/bin/env python3
# asyncio_generator_chain.py
import asyncio
@asyncio.coroutine
def outer():
print('in outer')
print('waiting for result1')
result1 = yield from phase1()
print('waiting for result2')
result2 = yield from phase2(result1)
return result1, result2
@asyncio.coroutine
def phase1():
print('in phase1')
return 'result1'
@asyncio.coroutine
def phase2(arg):
print('in phase2')
return 'result2 derived from {}'.format(arg)
event_loop = asyncio.get_event_loop()
try:
return_value = event_loop.run_until_complete(outer())
print('return value: {!r}'.format(return_value))
finally:
event_loop.close()
输出:
in outer
waiting for result1
in phase1
waiting for result2
in phase2
return value: ('result1', 'result2 derived from result1')