Syntaxerror await outside function как исправить

Hello I am new to python and am trying to work with a Dark Sky python API made by Detrous. When I run the demo code I am presented with an error:

forecast = await darksky.get_forecast(
              ^
SyntaxError: 'await' outside function

this error results from:

forecast = await darksky.get_forecast(
    latitude, longitude,
    extend=False, # default `False`
    lang=languages.ENGLISH, # default `ENGLISH`
    units=units.AUTO, # default `auto`
    exclude=[weather.MINUTELY, weather.ALERTS] # default `[]`
)

I am not too sure how to resolve this issue and am using python 3.

Thanks

asked Oct 19, 2019 at 6:19

NameIsMarcus's user avatar

3

I think this answer will be useful for people who search the same question as me.
To use async functions in synchronous context you can use event loop. You can write it from scratch for education purposes.
You can start from this answer
https://stackoverflow.com/a/51116910/14154287
And continue education with David Beazley books.

But developers of asyncio already did this for you.

import asyncio

loop = asyncio.get_event_loop()
forecast = loop.run_until_complete(darksky.get_forecast(...<here place arguments>...))
loop.close()

answered Sep 17, 2020 at 18:28

terehpp's user avatar

terehppterehpp

2313 silver badges7 bronze badges

1

The await keyword can be used only in asynchronous functions and methods. You can read more on asynchronous code to understand why.

The solution, without having any details about what you want to accomplish and how, is to use darksky = DarkSky(API_KEY) instead of darksky = DarkSkyAsync(API_KEY).

answered Oct 19, 2019 at 8:02

Krasen Penchev's user avatar

In newer versions of python (v3.7+), you can call async functions in sync contexts by using asyncio.run:

import asyncio

forecast = asyncio.run(darksky.get_forecast(...))

answered yesterday

Daniel González Fernández's user avatar

Learn how to fix the common SyntaxError: await outside function error in Python by understanding the proper usage of async and await keywords in asynchronous programming.

Table of Contents:

  • Understanding the Issue
  • Step-by-Step Guide to Fixing the Error
  • Step 1: Identify the Error
  • Step 2: Ensure Proper Use of Async/Await
  • Step 3: Use Asyncio.run() to Execute the Coroutine
  • FAQs

Understanding the Issue

The 'SyntaxError: await outside function' issue occurs when the await keyword is used outside of an async function. The await keyword is used to call asynchronous functions, also known as coroutines, and can only be used within another asynchronous function. To resolve this error, you must ensure that the await keyword is used within an async function and that the asynchronous function is executed using an appropriate asynchronous method, such as asyncio.run().

Read more about asynchronous programming in Python

Step-by-Step Guide to Fixing the Error

Follow these steps to fix the SyntaxError: await outside function error in your Python code.

Step 1: Identify the Error

First, locate the line of code that is causing the error. The error message will point you to the exact line where the await keyword is being used incorrectly.

Example error message:

  File "main.py", line 5
    response = await http_client.get('https://example.com')
              ^
SyntaxError: 'await' outside function

In this example, the error is caused by the await keyword being used on line 5.

Step 2: Ensure Proper Use of Async/Await

Make sure that the await keyword is being used within an async function. If the function containing the await keyword is not marked as async, add the async keyword to the function definition.

Example of incorrect usage:

import aiohttp

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

response = await fetch_data()
print(response)

Corrected usage:

import aiohttp

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

async def main():
    response = await fetch_data()
    print(response)

In the corrected example, the await keyword is used within the async function main().

Step 3: Use Asyncio.run() to Execute the Coroutine

Now that the await keyword is used within an async function, use asyncio.run() to execute the coroutine. This function is available in Python 3.7 and later.

Example:

import aiohttp
import asyncio

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

async def main():
    response = await fetch_data()
    print(response)

asyncio.run(main())

In this example, the main() coroutine is executed using asyncio.run().

FAQs

How do I use await within a synchronous function?

You cannot use await within a synchronous function. Convert the synchronous function to an asynchronous function by adding the async keyword to the function definition.

Can I use await in a Python script without defining a function?

No, you must use await within an async function. You can create an async function to wrap the asynchronous code and then execute the function using asyncio.run().

What is the difference between asyncio.run() and asyncio.ensure_future()?

asyncio.run() is a high-level function that runs a coroutine and returns the result. It should be used as the main entry point for running asynchronous code. asyncio.ensure_future() is a lower-level function that wraps a coroutine into a Task object, which can be scheduled for execution.

Can I use await with a synchronous function?

No, you can only use await with asynchronous functions or coroutines. If you need to call a synchronous function within an asynchronous function, consider using run_in_executor() to run the synchronous function in a separate thread.

Can I use await inside a list comprehension or generator expression?

No, you cannot use await inside a list comprehension or generator expression. Instead, use a regular for loop or consider using asyncio.gather() to execute multiple coroutines concurrently.

Learn more about asyncio.gather()

Опять-же есть у меня код евента.
Пишет ошибку: SyntaxError: await outside function.

# Event
@bot.event
async def on_message(message):
    await bot.process_commands(message)
    if message.author.id == bot.user.id:
        return

    if message.author.id in bot.blacklisted_users:
        return

    if f"<@!{bot.user.id}>" in message.content:
        data = cogs._json.read_json('prefixes')
        if str(message.guild.id) in data:
            prefix = data[str(message.guild.id)]

if __name__ == '__main__':
    for file in os.listdir(cwd+"/cogs"):
        if file.endswith(".py") and not file.startswith("_"):
            bot.load_extension(f"cogs.{file[:-3]}")

            if not message.author.bot and bot.user in message.mentions:
                embed = discord.Embed(title = f'Welcome!', timestamp = message.created_at, colour = discord.Colour.from_rgb(199, 182, 219),  description = f'''
                Hi {message.author.display_name}, my name **Osidium**!
                • My prefix - `o+`
                • Write the command `o+help` to find out all my features.
                • Want to know a little about me? Write `o-about`.
                • Need help on the bot, or found a bug/error? Visit our server: [Join](https://discord.gg/tYr5xeSS79)''')
                await message.reply(embed=embed)

@ymsaputra

I run the example in PySyft/examples/tutorials/advanced/websockets-example-MNIST-parallel/Asynchronous-federated-learning-on-MNIST.ipynb. However, there is a syntax error as follows:

File “coba_fed_async.py”, line 73
results = await asyncio.gather(
^
SyntaxError: ‘await’ outside function

I use Python 3.7.x. Is there any solution for this issue?

@fermat97

hi @ymsaputra did you find any solution? Hi @midokura-silvia do you have any idea? I got

results = await asyncio.gather(
                      ^
SyntaxError: invalid syntax

and I use python 3.6

@midokura-silvia

@ymsaputra await needs to be called from within a function. So in your file coba_fed_async.py your await calls need to be in a function that is marked as async.

@fermat97 this is not enough information to deduce where the syntax error is coming from.

@fermat97

@midokura-silvia I am using your code in Asynchronous-federated-learning-on-MNIST, however I don’t use as a notebook. There you have:

results = await asyncio.gather(
        *[
            rwc.fit_model_on_worker(
                worker=worker,
                traced_model=traced_model,
                batch_size=args.batch_size,
                curr_round=curr_round,
                max_nr_batches=args.federate_after_n_batches,
                lr=learning_rate,
            )
            for worker in worker_instances
        ]
    )

in this case await is used outside an async function. How didn’t you get any error?

@newne

@midokura-silvia I am using your code in Asynchronous-federated-learning-on-MNIST, however I don’t use as a notebook. There you have:

results = await asyncio.gather(
        *[
            rwc.fit_model_on_worker(
                worker=worker,
                traced_model=traced_model,
                batch_size=args.batch_size,
                curr_round=curr_round,
                max_nr_batches=args.federate_after_n_batches,
                lr=learning_rate,
            )
            for worker in worker_instances
        ]
    )

in this case await is used outside an async function. How didn’t you get any error?

I had the same error. but it worked in notebook.

@okazaki0

try to create async function and use inside the await i think it will work

@github-actions

This issue has been marked stale because it has been open 30 days with no activity. Leave a comment or remove the stale label to unmark it. Otherwise, this will be closed in 7 days.

@harshkasyap

@MusheerRepo

The syntax for using it is:

async def function_name:
Statement 1
Statement 2
.
.

asyncio.run(function_name())

Issue

I am trying to write a bot for Discord but I keep getting an error message:

File “bot.py”, line 33
await member.create_dm()
^
SyntaxError: ‘await’ outside async function

I am trying to get the bot to send a DM to a person who has just joined the server.

@client.event
@asyncio.coroutine
def on_member_join(member):
    await member.create_dm()
    member.dm_channel.send("Hi and welcome!")

I would very much appreciate your help.

Solution

Your code should look like this:

@client.event
@asyncio.coroutine
async def on_member_join(member):
    await member.create_dm()
    member.dm_channel.send("Hi and welcome!")

add async before def

for more information about async in python consider reading this: https://docs.python.org/3/library/asyncio-task.html

Answered By – Mogi

Добавить комментарий