async 异步函数/上下文
最后更新:2026-09-22
async 异步函数/上下文
async 用于声明 async def 函数或 async with 上下文。
| 分类 | 关键字与语句 |
|---|---|
| 类型 | 关键字与语句 |
| Python 版本 | 3.5+ |
📝 语法
async def name(params):
body
[async with expr as var: block]
▶ 示例
编辑下方代码,点击运行,在输出面板查看结果:
运行结果:
hi
🏷️ 相关关键字与语句
💡 相关案例
更多实战案例即将上线,敬请期待。
❓ 常见问题
Qasync def 和 def 有什么区别?
Aasync def 定义的是协程函数,调用它不会执行函数体,而是返回一个 coroutine 对象。必须 await 它,或用 asyncio.run() 驱动才会真正运行。
Q在模块顶层直接调用 async 函数为什么不执行?
A因为调用返回的是协程对象,而模块顶层不能直接用 await。正确做法是包一层:async def main(): ... 然后用 asyncio.run(main()) 运行。
Qasync 只能配 asyncio 用吗?
A不是。async/await 是语言语法,asyncio 只是最常用的事件循环实现;async with / async for 分别用于异步上下文管理和异步迭代。