简体   繁体   中英

Can I run Python Coroutines without asyncio?

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM