python runtime_error ai_generated true

SyntaxError: 'await' outside async function

ID: python/asyncio-await-outside-async

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.5+ active — — —

Root Cause

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

中文

在模块级别或非 async def 内使用 await;await 仅在 async def 内有效(或 notebook/repl 中顶层特殊支持)。

Workarounds

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

Dead Ends

Common approaches that don't work:

  1. 95% fail

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

  2. 95% fail

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