Python SyntaxError: ‘await’ outside async function

Updated: August 4, 2023 By: Khue Post a comment

This concise article is about a common error you might run into when writing asynchronous code in Python:

SyntaxError: 'await' outside async function

Understanding the Problem

await is used in an async function or method to wait on other asynchronous tasks, such as network requests, file operations, or database queries. However, you cannot use await in a regular (synchronous) function or method, or in the global scope of your script. This is because await requires a special context called an event loop, which is an object that manages the execution of coroutines, tasks, and callbacks.

The code snippet below causes the 'await' outside async function error since its uses await inside a synchronous function:

def do_something():
    await asyncio.sleep(1)
    print("Hello")

This one makes the error happen, too, because it uses await in the global scope:

import asyncio

await asyncio.sleep(1)

Let’s see how we can get through this problem in the next section of this article.

How to solve the error?

To fix SyntaxError: ‘await’ outside async function, you need to ensure that the await keyword is used inside an async function or method. If you are calling an async function or method outside of an async function or method, you need to use the asyncio.run() function to call the async function or method. In general, you need to write code like this:

import asyncio


# Define an async function
async def foo():
    # Use await inside the async function
    await bar()


# Define another async function
async def bar():
    # Do something asynchronously
    await asyncio.sleep(2)
    print("Welcome to Sling Academy!")


# Call the async function from another async function using await
async def main():
    await foo()


# Call the async function from the script using asyncio.run ()
asyncio.run(main())

Let’s examine another example to get a better understanding. Suppose you have an async function called get_response() that returns a response from a web API using aiohttp (you can install this library with pip install aiohttop):

import aiohttp


async def get_response():
    # Create an aiohttp client session
    async with aiohttp.ClientSession() as ses:
        # Send a GET request to the web API
        async with ses.get("https://api.slingacademy.com") as resp:
            # Return the response as a JSON object
            return (await resp.json())["response"]

If you try to call this function directly from your script, like this:

print (await get_response())

You will get the SyntaxError: ‘await’ outside async function error, because you are using await in the global scope of your script.

To get through this error, you need to wrap your code in an async function, such as main(), and then call it using asyncio.run(), like so:

# SlingAcademy.com
# This code uses Python 3.11.4

import asyncio
import aiohttp


async def get_response():
    # Create an aiohttp client session
    async with aiohttp.ClientSession() as ses:
        # Send a GET request to the web API
        async with ses.get("https://api.slingacademy.com") as resp:
            # Return the response as a JSON object
            return (await resp.json())

# Call the get_response() function inside the main() function
async def main():
    # Call the get_response() function using await
    response = await get_response()

    # Print the response
    print(response)


# Call the main() function using asyncio.run()
asyncio.run(main())

Output:

{'success': True, 'message': 'Welcome to Sling Academy Public API'}

Conclusion

I hope this short article has helped you understand and fix the SyntaxError: ‘await’ outside async function error in Python. If you find something outdated or incorrect, please let me know by leaving a comment. Happy coding & have a nice day!