Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 429
NameIsMarcus Avatar asked Oct 19 '19 06:10

NameIsMarcus


1 Answers

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()
like image 142
terehpp Avatar answered Oct 13 '22 00:10

terehpp