python runtime_error ai_generated true

SyntaxError: 'await' 在 async 函数之外

SyntaxError: 'await' outside async function

ID: python/asyncio-await-outside-async

其他格式: JSON · Markdown 中文 · English
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).

generic

解决方案

  1. 97% 成功率
    import asyncio
    
    async def main():
        await some_coro()
    
    asyncio.run(main())
  2. 93% 成功率
    import asyncio
    result = asyncio.run(some_coro())

无效尝试

常见但无效的做法:

  1. 95% 失败

    This is a parser-level SyntaxError, not a type error; comments cannot suppress it.

  2. 95% 失败

    SyntaxError occurs at compile time before any except block is entered.