Python 3.5+ 协程 ( coroutines ) 之 async with 表达式

yufei       5 年, 9 月 前       3265

Python 3.5+ 及以上版本中可以使用协程,而在 Python 3.5+ 协程 ( coroutines ) 之协程函数 ( async def ) 篇章中我们也提到,可以在协程函数中使用 async with 表达式

async with 表达式又称之为 异步上下文管理器

async with 表达式

async with 表达式的语法格式为

async_with_stmt ::=  "async" with_stmt

我们知道,with 是一个上下文管理器,所以呢,async with 就是一个异步上下文管理器

异步上下文管理器是一种上下文管理器,能够在其进入 __enter__() 和退出方法 __exit()__ 中暂停执行

使用范例一般如下

async with EXPR as VAR:
    BLOCK

上面这段代码类似于

mgr = (EXPR)
aexit = type(mgr).__aexit__
aenter = type(mgr).__aenter__(mgr)

VAR = await aenter
try:
    BLOCK
except:
    if not await aexit(mgr, *sys.exc_info()):
        raise
else:
    await aexit(mgr, None, None, None)

with 中的上下文管理器需要定义两个方法 __enter__()__exit__() 一样

异步上下文管理器同样也需要实现 __aenter__()__aexit__() 方法

关于这两个方法的介绍,我们会在后面的章节中详细说明

需要说明的是,async with 异步上下文管理器同样只能在 协程函数 中使用,否则会报语法错误 ( SyntaxError )

范例

使用 async with 之前我们先要定义一个异步上下文管理器

import asyncio

async def log(some_thing):
    print(some_thing)

class AsyncContextManager:
    async def __aenter__(self):
        await log('entering context')

    async def __aexit__(self, exc_type, exc, tb):
        await log('exiting context')


async def run_async_with():
    async with AsyncContextManager() as c:
        print("使用 async with 来管理异步上下文")

定义了异步上下文管理器之后,我们就可以使用 async with 表达式了

async def run_async_with():
    async with AsyncContextManager() as c:
        print("使用 async with 来管理异步上下文")

全部代码如下

import asyncio

async def log(some_thing):
    print(some_thing)

class AsyncContextManager:
    async def __aenter__(self):
        await log('entering context')

    async def __aexit__(self, exc_type, exc, tb):
        await log('exiting context')


async def run_async_with():

    async with AsyncContextManager() as c:
        print("使用 async with 来管理异步上下文")

loop = asyncio.get_event_loop()
loop.run_until_complete(run_async_with())
loop.close()

运行上面的范例,输出结果如下

entering context
使用 async with 来管理异步上下文
exiting context
目前尚无回复
简单教程 = 简单教程,简单编程
简单教程 是一个关于技术和学习的地方
现在注册
已注册用户请 登入
关于   |   FAQ   |   我们的愿景   |   广告投放   |  博客

  简单教程,简单编程 - IT 入门首选站

Copyright © 2013-2022 简单教程 twle.cn All Rights Reserved.