python runtime_error ai_generated true

SyntaxError: 'await' 出现在 async 函数之外

SyntaxError: 'await' outside async function

ID: python/asyncio-await-outside-async-function

其他格式: JSON · Markdown 中文 · English
80%修复率
92%置信度
0证据数
2024-01-09首次发现

版本兼容性

版本状态引入弃用备注
3.8 active — — —
3.9 active — — —
3.10 active — — —
3.11 active — — —
3.12 active — — —

根因分析

await 关键字被用在普通的 def 函数或模块顶层。await 只能在 async def 函数体内使用(或在 IPython/Jupyter 的顶层 await 中)。

English

The await keyword was used in a regular def function or at module top level. await is only valid inside async def bodies (or in top-level await when using IPython/Jupyter).

generic

解决方案

  1. 95% 成功率
    async def handler():
        data = await fetch()
        return data
  2. 93% 成功率
    async def main():
        await fetch()
    if __name__ == '__main__':
        asyncio.run(main())
  3. 90% 成功率
    # IPython/Jupyter supports top-level await in cells
    await fetch()

无效尝试

常见但无效的做法:

  1. 75% 失败

    If the sync function is itself called from async code, this raises 'This event loop is already running'.

  2. 95% 失败

    Coroutine objects have no result() method; raises AttributeError.