Python 如何让 contextmanager 支持异步上下文

15次阅读

python中实现异步上下文管理应使用@asynccontextmanager(Python 3.7+)或手动实现__aenter__/__aexit__方法,禁用@contextmanager处理async with;需确保协程调用、单次yield及异常传播正确。

Python 如何让 contextmanager 支持异步上下文

Python 的 @contextmanager 装饰器本身不支持异步上下文(即 async with),因为它设计用于同步生成器。要实现异步上下文管理,需改用 @asynccontextmanager —— 这是 contextlib 模块从 Python 3.7 开始提供的专用工具

使用 @asynccontextmanager 替代 @contextmanager

这是最直接、标准的方案。它接受一个 async def 函数,该函数必须包含恰好一个 yield,且 yield 后的值将作为 async with 语句中 as 绑定的对象

  • 确保函数是 async def,且内部可使用 await(如异步初始化、清理)
  • yield 必须存在,且只能出现一次;yield 后的表达式(如有)即为上下文对象
  • 异常会正常传播,yield 后的代码相当于 __aexit__,可用于异步清理

示例:

from contextlib import asynccontextmanager 

@asynccontextmanager async def db_connection(): conn = await acquire_db_connection() # 假设这是个协程 try: yield conn finally: await conn.close() # 异步清理

使用方式

async def main(): async with db_connection() as conn: await conn.execute("select 1")

手动实现 __aenter____aexit__

若需更精细控制(如状态保持、多次重用、非生成器逻辑),可定义普通类并实现两个异步方法。

立即学习Python免费学习笔记(深入)”;

  • __aenter__ 应返回 awaitable,通常用 return await ... 或直接返回协程
  • __aexit__ 必须是 async def,接收 exc_type, exc_value, traceback,返回 True 可抑制异常
  • 类实例无需可调用,但需确保生命周期清晰(避免意外重复进入)

示例:

class AsyncFile:     def __init__(self, path):         self.path = path         self.file = None 
async def __aenter__(self):     self.file = await aiofiles.open(self.path, 'r')     return self.file  async def __aexit__(self, exc_type, exc_val, exc_tb):     if self.file:         await self.file.close()

使用

async with AsyncFile('data.txt') as f: content = await f.read()

注意兼容性与常见误区

混用同步和异步上下文管理器会导致运行时错误(如 TypeError: Object X is not async context manager)。

  • 不要对 @contextmanager 包裹的函数加 async def —— 它无法被 async with 识别
  • Python @asynccontextmanager,需自行实现或升级解释器
  • 若底层资源本身不支持异步(如普通文件 I/O),强行套异步装饰器无意义,应优先使用真正异步的库(如 aiofilesaiomysql

组合多个异步上下文(类似 ExitStack

标准 ExitStack 不支持异步。如需动态管理多个异步上下文,可用 async_exit_stack 第三方包,或手动维护协程列表:

  • 收集所有 __aenter__ 协程,用 await asyncio.gather(...) 并发进入
  • 退出时按反序 await 每个 __aexit__,并正确处理异常传播
  • 生产环境建议使用成熟方案如 async_exit_stack(PyPI 可安装),避免手动出错

text=ZqhQzanResources