Python异步处理中的async with 和async for 用法说明

来源:互联网 发布:三体电影知乎 编辑:程序博客网 时间:2024/06/07 08:01

本文转载自http://blog.csdn.net/tinyzhao/article/details/52684473

本文翻译自Python的开发者指南PEP 492。


网上async with和async for的中文资料比较少,我把PEP 492中的官方陈述翻译一下。

异步上下文管理器”async with”

异步上下文管理器指的是在enterexit方法处能够暂停执行的上下文管理器。

为了实现这样的功能,需要加入两个新的方法:__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')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

新语法

异步上下文管理器使用一种新的语法:

async with EXPR as VAR:    BLOCK
  • 1
  • 2

这段代码在语义上等同于:

mgr = (EXPR)aexit = type(mgr).__aexit__aenter = type(mgr).__aenter__(mgr)exc = TrueVAR = await aentertry:    BLOCKexcept:    if not await aexit(mgr, *sys.exc_info()):        raiseelse:    await aexit(mgr, None, None, None)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

和常规的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)        ...
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

需要使用锁的代码也很简单:

async with lock:    ...
  • 1
  • 2

而不是:

with (yield from lock):    ...
  • 1
  • 2

异步迭代器 “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):        ...
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

新语法

通过异步迭代器实现的一个新的迭代语法如下:

async for TARGET in ITER:    BLOCKelse:    BLOCK2
  • 1
  • 2
  • 3
  • 4

这在语义上等同于:

iter = (ITER)iter = type(iter).__aiter__(iter)running = Truewhile running:    try:        TARGET = await type(iter).__anext__(iter)    except StopAsyncIteration:        running = False    else:        BLOCKelse:    BLOCK2
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

把一个没有__aiter__方法的迭代对象传递给 async for将引起TypeError。如果在async def函数外面使用async with,将引起一个SyntaxError(语法错误)。

和常规的for表达式一样, async for也有一个可选的else 分句。.

例子1

使用异步迭代器能够在迭代过程中异步地缓存数据:

async for data in cursor:    ...
  • 1
  • 2

这里的cursor是一个异步迭代器,能够从一个数据库中每经过N次迭代预取N行数据。

下面的语法展示了这种新的异步迭代协议的用法:

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()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

接下来这个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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

例子2

下面的代码可以将常规的迭代对象变成异步迭代对象。尽管这不是一个非常有用的东西,但这段代码说明了常规迭代器和异步迭代器之间的关系。

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 valueasync for letter in AsyncIteratorWrapper("abc"):    print(letter)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

为什么要抛出StopAsyncIteration?

协程(Coroutines)内部仍然是基于生成器的。因此在PEP 479之前,下面两种写法没有本质的区别:

def g1():    yield from fut    return 'spam'
  • 1
  • 2
  • 3

def g2():    yield from fut    raise StopIteration('spam')
  • 1
  • 2
  • 3

自从 PEP 479 得到接受并成为协程 的默认实现,下面这个例子将StopIteration包装成一个RuntimeError

async def a1():    await fut    raise StopIteration('spam')    
  • 1
  • 2
  • 3

告知外围代码迭代已经结束的唯一方法就是抛出StopIteration。因此加入了一个新的异常类StopAsyncIteration

由PEP 479的规定 , 所有协程中抛出的StopIteration异常都被包装在RuntimeError中。


本文转载自http://blog.csdn.net/tinyzhao/article/details/52684473

阅读全文
0 0
原创粉丝点击