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:
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