-1

Can I skip the async def keyword in a Python 3.5 function, and my code will still work asynchronously?

Something like this:

async def sleep():
    await asyncio.sleep(1)

def mysleep():
    loop = asyncio.get_event_loop()
    loop.await(sleep)

def main():
    mysleep()
speller
  • 1,641
  • 2
  • 20
  • 27

1 Answers1

4

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.

Mikhail Gerasimov
  • 36,989
  • 16
  • 116
  • 159