Python3异步解析式/生成器

Python 3.6添加了异步解析式PEP 530和异步生成器PEP 525

异步解析式

Example:

result = [i async for i in aiter() if i % 2]

当然,所有解析式都支持await表达式

import asyncio
 
async def numbers(numbers):
    for i in range(numbers):
        yield i
        await asyncio.sleep(0.5)
 
async def main():
    odd_numbers = [i async for i in numbers(10) if i % 2]
    print(odd_numbers)
 
if __name__ == '__main__':
    event_loop = asyncio.get_event_loop()
    try:
        event_loop.run_until_complete(main())
    finally:
        event_loop.close()

异步生成器

async def ticker(delay, to):
    for i in range(to):
        yield i
        await asyncio.sleep(delay)


async def run():
    async for i in ticker(1, 10):
        print(i)


import asyncio
loop = asyncio.get_event_loop()
try:
    loop.run_until_complete(run())
finally:
    loop.close()

Ref: What’s New in Python: Asynchronous Comprehensions / Generators