8

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

NameIsMarcus
  • 93
  • 1
  • 1
  • 5

2 Answers2

12

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()
terehpp
  • 191
  • 2
  • 7
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).