python
runtime_error
ai_generated
true
SyntaxError: 'await' outside async function
ID: python/asyncio-await-in-non-async
80%Fix Rate
90%Confidence
0Evidence
2024-05-01First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 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
-
100% success Define the function with async def
async def fetch_data(): return await some_async_func()
-
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:
-
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.
-
Using yield from instead of await
70% fail
yield from works with generators, not async functions; it will raise a different error.