As Vincent noticed if you change your code like this it'll work without error:
import asyncio
async def sleep():
await asyncio.sleep(1)
def mysleep():
loop = asyncio.get_event_loop()
loop.run_until_complete(sleep())
def main():
mysleep()
if __name__ == '__main__':
main()
But does it mean it works asynchronously?
Answer is — it works asynchronously only inside mysleep()
function (and can get related benefit there), but it's blocking for everything outside of mysleep()
. It means that mysleep()
itself or any outer code can't be run asynchronously alongside with other asynchronous functions.
To avoid this situation you should run your event loop in most possible outer scope: make event loop starting at the entry point of your program. It'll make possible to run everything asynchronously inside this single event loop.