Reputation: 163
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
Upvotes: 15
Views: 38216
Reputation: 342
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(...))
Upvotes: 1
Reputation: 261
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()
Upvotes: 19
Reputation: 21
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)
.
Upvotes: 2