type
Post
status
Published
date
Apr 20, 2026
slug
python007
summary
tags
python
category
python
icon
password
example-row
@asynccontextmanager 装饰器的作用:简化异步上下文管理器的创建
来自 Python 标准库:
没有 @asynccontextmanager 时,需要这样写:
使用 @asynccontextmanager 后,简化为:
工作原理:
  1. yield 之前:相当于 __aenter__,执行进入逻辑。
  1. yield 返回值:作为 as 变量的值。
  1. yield 之后:相当于 __aexit__,执行退出逻辑。
  1. 异常处理:try-except 块捕获异常,类似 __aexit__ 的参数。
优势:
  • 代码更简洁。
  • 不需要单独定义类。
  • 逻辑更直观(从上到下阅读)。
总结:
@asynccontextmanager 将一个生成器函数转换为异步上下文管理器,避免了手动实现 __aenter__ 和 __aexit__ 方法。
 
【python006】Bert推理【blog001】Windows下hexo+github
Loading...