python runtime_error ai_generated true

SyntaxError: 'await' outside async function

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
90%Confidence
0Evidence
2024-05-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.8 active
3.9 active
3.10 active
3.11 active
3.12 active

Root Cause

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

generic

中文

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

Workarounds

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

Dead Ends

Common approaches that don't work:

  1. Decorating the function with @asyncio.coroutine 90% fail

    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% fail

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