SyntaxPython Error

SyntaxError

SyntaxError: 'await' outside function

Traceback

terminal
Traceback (most recent call last):
  File "main.py", line 3, in <module>
    response = await aiohttp.get("https://example.com")
SyntaxError: 'await' outside function

What causes this error

The `await` keyword was used outside an `async def` function, or async syntax was used in a non-async context. Only async functions can use await.

How to fix it

Define the function with `async def`. Use `asyncio.run()` to call async functions from synchronous code. In Jupyter/IPython, `await` works at the top level. Use an async framework (asyncio, trio) properly.

Code that causes this error

Broken
import aiohttp

response = await aiohttp.get("https://example.com")

Fixed code

Fixed
import asyncio
import aiohttp

async def fetch():
    async with aiohttp.ClientSession() as session:
        async with session.get("https://example.com") as response:
            return await response.text()

result = asyncio.run(fetch())

About SyntaxError

This SyntaxError is raised when `await` is used outside of an `async def` function, or when `async for` / `async with` appear in non-async contexts. The `await` keyword can only be used inside functions defined with `async def`. In Python 3.10+, `await` can also be used at the top level in asyncio REPL mode and in Jupyter notebooks.

Common scenarios that trigger this error include forgetting to mark a function as async, using await in a regular function that calls async code, and trying to use await at the module level in a script. To run async code from a synchronous context, use `asyncio.run(coroutine())` or `asyncio.get_event_loop().run_until_complete(coroutine())`. The async/await model is Python's approach to cooperative multitasking.

Common scenarios

1

Writing code with missing colons, parentheses, or brackets

2

Mixing Python 2 and Python 3 syntax when upgrading a codebase

3

Copy-pasting code from the web with formatting issues or invisible characters

4

Using reserved keywords as variable or function names

Related errors