python
runtime_error
ai_generated
true
SyntaxError: 'await' 在 async 函数之外
SyntaxError: 'await' outside async function
ID: python/asyncio-await-outside-async
80%修复率
90%置信度
0证据数
2024-01-30首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.5+ | active | — | — | — |
根因分析
在模块级别或非 async def 内使用 await;await 仅在 async def 内有效(或 notebook/repl 中顶层特殊支持)。
English
Using await at module level or inside a non-async def; await is only valid inside async def (or top-level in a notebook/repl with special support).
解决方案
-
97% 成功率
import asyncio async def main(): await some_coro() asyncio.run(main()) -
93% 成功率
import asyncio result = asyncio.run(some_coro())
无效尝试
常见但无效的做法:
-
95% 失败
This is a parser-level SyntaxError, not a type error; comments cannot suppress it.
-
95% 失败
SyntaxError occurs at compile time before any except block is entered.