python runtime_error ai_generated true

语法错误:'await' 在异步函数外部

SyntaxError: 'await' outside async function

ID: python/asyncio-await-in-non-async

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

版本兼容性

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

根因分析

在同步函数内或模块级别使用 await 关键字,而没有包含它的 async def,违反了 Python 语法规则。

English

Using the await keyword inside a synchronous function or at module level without an enclosing async def, violating Python syntax rules.

generic

解决方案

  1. 100% 成功率 Define the function with async def
    async def fetch_data(): return await some_async_func()
  2. 95% 成功率 Use asyncio.run() at module level with a wrapper
    async def main(): await fetch_data()
    if __name__ == '__main__': asyncio.run(main())

无效尝试

常见但无效的做法:

  1. Decorating the function with @asyncio.coroutine 90% 失败

    The @asyncio.coroutine decorator is deprecated and does not make a function async; await still requires async def.

  2. Using yield from instead of await 70% 失败

    yield from works with generators, not async functions; it will raise a different error.