深刻Asyncio(十)異步解析式

Async Comprehensions

目前已經學會了如何在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)}
  1. 這是個簡單的異步生成器;bash

  2. sleep一會,確保這是個異步函數;異步

  3. 觀察如何用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]
  1. 一個簡單的協程函數;oop

  2. 異步生成器;code

  3. 返回一個包含函數和參數的tuple;協程

  4. fac(3)返回一個異步生成器,必須用異步for調用,返回值是幾個tuple,經過參數中的函數調用生成一個coroutine,用await處理coroutine,awaitasync for作的是徹底不相關的事。ci

相關文章
相關標籤/搜索