python
runtime_error
ai_generated
true
SyntaxError: 'await' outside async function
ID: python/asyncio-await-outside-async-function
80%Fix Rate
92%Confidence
0Evidence
2024-01-09First 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
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中文
await 关键字被用在普通的 def 函数或模块顶层。await 只能在 async def 函数体内使用(或在 IPython/Jupyter 的顶层 await 中)。
Workarounds
-
95% success
async def handler(): data = await fetch() return data -
93% success
async def main(): await fetch() if __name__ == '__main__': asyncio.run(main()) -
90% success
# IPython/Jupyter supports top-level await in cells await fetch()
Dead Ends
Common approaches that don't work:
-
75% fail
If the sync function is itself called from async code, this raises 'This event loop is already running'.
-
95% fail
Coroutine objects have no result() method; raises AttributeError.