Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Proper use of async

I have a main function that doesn’t need to be async, but this function calls several other functions that do need to be async.

What would be the better practice: to make main async and call asyncio.run(main()) in if __name__ ... or would it be better to not make main async (it has nothing to do while awaiting) and call asyncio.run() for each async function call made from main?

In other words, something like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

async def func1():
    await something

async def func2():
    await something

async def main():
    x = input()
    if x == "y":
        await func1()
    else:
        await func2()

if __name__ == "__main__":
    asyncio.run(main())

Or this:

async def func1():
    await something

async def func2():
    await something

def main():
    x = input()
    if x == "y":
        asyncio.run(func1())
    else:
        asyncio.run(func2())

if __name__ == "__main__":
    main()

>Solution :

As Python docs said

The asyncio.run() function to run the top-level entry point “main()” function (see the above example.)

That’s mainly because of:

This function cannot be called when another asyncio event loop is running in the same thread.

So, your first example with asyncio.run(main()) is more Pythonic and should be used

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading