SyntaxError: 'await' outside function
Asked Answered
L

3

15

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

Lanai answered 19/10, 2019 at 6:19 Comment(3)
await should always be inside an async functionMoonwort
Can you try by removing await before darksky.get_forecast(Portent
try putting the whole code you presented here inside a function async def main() then call itKindergarten
A
18

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://mcmap.net/q/49739/-how-does-asyncio-actually-work 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()
Antimasque answered 17/9, 2020 at 18:28 Comment(1)
If you use Python 3,7 or later, this can be simplified to asyncio.run(darksky.get_forecast(...))Tuscarora
R
2

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).

Redd answered 19/10, 2019 at 8:2 Comment(0)
C
1

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(...))
Coffer answered 22/5, 2023 at 11:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.