這篇文章給大家分享的是有關(guān)python中async with和async for怎么用的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過來看看吧。
異步上下文管理器”async with”
異步上下文管理器指的是在enter和exit方法處能夠暫停執(zhí)行的上下文管理器。
為了實(shí)現(xiàn)這樣的功能,需要加入兩個(gè)新的方法:__aenter__ 和__aexit__。這兩個(gè)方法都要返回一個(gè) awaitable類型的值。
異步上下文管理器的一種使用方法是:
class AsyncContextManager: async def __aenter__(self): await log('entering context') async def __aexit__(self, exc_type, exc, tb): await log('exiting context')
新語法
異步上下文管理器使用一種新的語法:
async with EXPR as VAR: BLOCK
這段代碼在語義上等同于:
mgr = (EXPR) aexit = type(mgr).__aexit__ aenter = type(mgr).__aenter__(mgr) exc = True VAR = await aenter try: BLOCK except: if not await aexit(mgr, *sys.exc_info()): raise else: await aexit(mgr, None, None, None)
和常規(guī)的with表達(dá)式一樣,可以在一個(gè)async with表達(dá)式中指定多個(gè)上下文管理器。
如果向async with表達(dá)式傳入的上下文管理器中沒有__aenter__ 和__aexit__方法,這將引起一個(gè)錯(cuò)誤 。如果在async def函數(shù)外面使用async with,將引起一個(gè)SyntaxError(語法錯(cuò)誤)。
例子
使用async with能夠很容易地實(shí)現(xiàn)一個(gè)數(shù)據(jù)庫事務(wù)管理器。
async def commit(session, data): ... async with session.transaction(): ... await session.update(data) ...
需要使用鎖的代碼也很簡(jiǎn)單:
async with lock: ...
而不是:
with (yield from lock): ...
異步迭代器 “async for”
一個(gè)異步可迭代對(duì)象(asynchronous iterable)能夠在迭代過程中調(diào)用異步代碼,而異步迭代器就是能夠在next方法中調(diào)用異步代碼。為了支持異步迭代:
1、一個(gè)對(duì)象必須實(shí)現(xiàn)__aiter__方法,該方法返回一個(gè)異步迭代器(asynchronous iterator)對(duì)象。
2、一個(gè)異步迭代器對(duì)象必須實(shí)現(xiàn)__anext__方法,該方法返回一個(gè)awaitable類型的值。
3、為了停止迭代,__anext__必須拋出一個(gè)StopAsyncIteration異常。
異步迭代的一個(gè)例子如下:
class AsyncIterable: def __aiter__(self): return self async def __anext__(self): data = await self.fetch_data() if data: return data else: raise StopAsyncIteration async def fetch_data(self): ...
新語法
通過異步迭代器實(shí)現(xiàn)的一個(gè)新的迭代語法如下:
async for TARGET in ITER: BLOCK else: BLOCK2
這在語義上等同于:
iter = (ITER) iter = type(iter).__aiter__(iter) running = True while running: try: TARGET = await type(iter).__anext__(iter) except StopAsyncIteration: running = False else: BLOCK else: BLOCK2
把一個(gè)沒有__aiter__方法的迭代對(duì)象傳遞給 async for將引起TypeError。如果在async def函數(shù)外面使用async with,將引起一個(gè)SyntaxError(語法錯(cuò)誤)。
和常規(guī)的for表達(dá)式一樣, async for也有一個(gè)可選的else 分句。.
例子1
使用異步迭代器能夠在迭代過程中異步地緩存數(shù)據(jù):
async for data in cursor: ...
這里的cursor是一個(gè)異步迭代器,能夠從一個(gè)數(shù)據(jù)庫中每經(jīng)過N次迭代預(yù)取N行數(shù)據(jù)。
下面的語法展示了這種新的異步迭代協(xié)議的用法:
class Cursor: def __init__(self): self.buffer = collections.deque() async def _prefetch(self): ... def __aiter__(self): return self async def __anext__(self): if not self.buffer: self.buffer = await self._prefetch() if not self.buffer: raise StopAsyncIteration return self.buffer.popleft()
接下來這個(gè)Cursor 類可以這樣使用:
async for row in Cursor(): print(row) which would be equivalent to the following code: i = Cursor().__aiter__() while True: try: row = await i.__anext__() except StopAsyncIteration: break else: print(row)
例子2
下面的代碼可以將常規(guī)的迭代對(duì)象變成異步迭代對(duì)象。盡管這不是一個(gè)非常有用的東西,但這段代碼說明了常規(guī)迭代器和異步迭代器之間的關(guān)系。
class AsyncIteratorWrapper: def __init__(self, obj): self._it = iter(obj) def __aiter__(self): return self async def __anext__(self): try: value = next(self._it) except StopIteration: raise StopAsyncIteration return value async for letter in AsyncIteratorWrapper("abc"): print(letter)
為什么要拋出StopAsyncIteration?
協(xié)程(Coroutines)內(nèi)部仍然是基于生成器的。因此在PEP 479之前,下面兩種寫法沒有本質(zhì)的區(qū)別:
def g1(): yield from fut return 'spam'
和
def g2(): yield from fut raise StopIteration('spam')
自從 PEP 479 得到接受并成為協(xié)程 的默認(rèn)實(shí)現(xiàn),下面這個(gè)例子將StopIteration包裝成一個(gè)RuntimeError。
async def a1(): await fut raise StopIteration('spam')
告知外圍代碼迭代已經(jīng)結(jié)束的唯一方法就是拋出StopIteration。因此加入了一個(gè)新的異常類StopAsyncIteration。
由PEP 479的規(guī)定 , 所有協(xié)程中拋出的StopIteration異常都被包裝在RuntimeError中。
感謝各位的閱讀!關(guān)于“python中async with和async for怎么用”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!
本文標(biāo)題:python中asyncwith和asyncfor怎么用-創(chuàng)新互聯(lián)
文章源于:http://www.chinadenli.net/article42/diddec.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供移動(dòng)網(wǎng)站建設(shè)、云服務(wù)器、品牌網(wǎng)站建設(shè)、網(wǎng)站營銷、全網(wǎng)營銷推廣、品牌網(wǎng)站制作
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容