3

I'm trying understand if asyncio is a necessary part of the Python definition of coroutines or simply a convenience package.

Can I run this program without asyncio?

import time

async def clk():
    time.sleep(0.1)

async def process():
    for _ in range(2):
        await clk();
        time.sleep(0.2)
        print("I am DONE waiting!")

def run():
    await process()

if __name__ == "__main__":
    run()

I get the error that run() is not defined with async, which I get, but there seems to be an infinite regress to the top. Interestingly, this code runs (without the run() function) in Jupyter notebook. I just type await process.

1
  • 1
    You need some kind of event loop to run coroutines, and asyncio provides the standard one (see e.g. asyncio.run). Jupyter conveniently hides this from you, but it still executes it with the help of asyncio: ipython.readthedocs.io/en/stable/interactive/… Commented Jan 17, 2021 at 14:21

1 Answer 1

2

To run async functions, you need to provide an event loop. One of the main functionalities of asyncio is to provide such a loop: when you execute asyncio.run(process) it provides a loop internally.

The reason why this code works in a notebook is that Jupyter (as well as the ipython REPL) provides a loop under the hood; there are other third-party libraries that provide a loop, such as trio and curio.

That being said, you can freely provide your own loop instead of using a library, as demonstrated in this answer. But in practice there is no point in doing that as asyncio is part of the Python standard library.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.