网上async with和async for的中文资料比较少,我把PEP 492中的官方陈述翻译一下。
异步上下文管理器”async with”
异步上下文管理器指的是在enter和exit方法处能够暂停执行的上下文管理器。
为了实现这样的功能,需要加入两个新的方法:__aenter__ 和__aexit__。这两个方法都要返回一个 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)
和常规的with表达式一样,可以在一个async with表达式中指定多个上下文管理器。
如果向async with表达式传入的上下文管理器中没有__aenter__ 和__aexit__方法,这将引起一个错误 。如果在async def函数外面使用async with,将引起一个SyntaxError(语法错误)。
例子
使用async with能够很容易地实现一个数据库事务管理器。
async def commit(session, data): ... async with session.transaction(): ... await session.update(data) ...
需要使用锁的代码也很简单:
async with lock: ...
而不是:
with (yield from lock): ...
异步迭代器 “async for”
一个异步可迭代对象(asynchronous iterable)能够在迭代过程中调用异步代码,而异步迭代器就是能够在next方法中调用异步代码。为了支持异步迭代:
1、一个对
象必须实现__aiter__方法,该方法返回一个异步迭代器(asynchronous iterator)对象。
2、一个异步迭代器对象必须实现__anext__方法,该方法返回一个awaitable类型的值。
3、为了停止迭代,__anext__必须抛出一个StopAsyncIteration异常。
异步迭代的一个例子如下:
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): ...
新语法
通过异步迭代器实现的一个新的迭代语法如下:
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
把一个没有__aiter__方法的迭代对象传递给 async for将引起TypeError。如果在async def函数外面使用async with,将引起一个SyntaxError(语法错误)。