Author: lightless@Meili-inc
0x00 前言
0x01 起:一切从生成器开始
def my_range(max_number):
sequence = []
index = 0
while index < max_number:
sequence.append(index)
index += 1
return sequence
def lazy_range(max_number):
index = 0
while index < max_number:
yield index
index += 1
当函数执行遇到yield的时候,会暂停执行。这样只需在内存中维护可以存储一个整数的内存空间就可以了。如果对生成器/迭代器不理解的话,可以参考Stack Overflow上的这篇高票回答:传送门
0x02 承:协程诞生
def smart_range(max_number):
index = 0
while index < max_number:
jump = yield index
if jump is None:
jump = 1
index += jump
def lazy_range(max_number):
index = 0
def gratuitous_refactor():
while index < max_number:
yield index
index += 1
yield from gratuitous_refactor()
import asyncio
@asyncio.coroutine
def counttdown(number, n):
while n > 0:
print("T-minus", n, "({})".format(number))
yield from asyncio.sleep(1)
n -= 1
loop = asyncio.get_event_loop()
tasks = [
asyncio.ensure_future(counttdown("A", 2)),
asyncio.ensure_future(counttdown("B", 5)),
]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
0x03 转:从yield from到await
# python34
@asyncio.coroutine
def py34_function():
yield from work()
# python35
async def py35_function():
await work()
result = [i async for i in aiter() if i % 2]
result = [await func() for fun in funcs if await condition()]
async def test(x, y):
for i in range(y):
yield i
await asyncio.sleep(x)
0x04 合:尾声