目前已經學會了如何在Python中進行異步迭代,接下來的問題是這是否適用於解析式?答案是OJBK!該支持在PEP 530中說起,建議去讀一下。編程
>>> import asyncio >>> async def doubler(n): # 1 ... for i in range(n): ... yield i, i*2 ... await asyncio.sleep(0.1) # 2 >>> async def main(): ... result = [x async for x in doubler(3)] # 3 ... print(result) ... result = {x: y async for x, y in doubler(3)} ... print(result) ... result = {x async for x in doubler(3)} ... print(result) >>> asyncio.get_event_loop().run_until_complete(main()) [(0, 0), (1, 2), (2, 4)] {0: 0, 1: 2, 2: 4} {(1, 2), (0, 0), (2, 4)}
這是個簡單的異步生成器;bash
sleep一會,確保這是個異步函數;異步
觀察如何用async for替代for;async
在PEP 530後半段有介紹在解析式中使用await
,但要注意的是,await
只能在async def
函數體中使用。異步編程
繼續用例子來熟悉異步編程語法。函數
>>> import asyncio >>> async def f(x): # 1 ... await asyncio.sleep(0.1) ... return x + 100 >>> async def fac(n): # 2 ... for x in range(n): ... await asyncio.sleep(0.1) ... yield f, x # 3 >>> async def main(): ... results = [await f(x) async for f, x in fac(3)] # 4 ... print('results=', results) >>> asyncio.get_event_loop().run_until_complete(main()) results= [100, 101, 102]
一個簡單的協程函數;oop
異步生成器;code
返回一個包含函數和參數的tuple;協程
fac(3)
返回一個異步生成器,必須用異步for調用,返回值是幾個tuple,經過參數中的函數調用生成一個coroutine,用await
處理coroutine,await
與async for
作的是徹底不相關的事。ci