The Python docs give this code example:
import asyncio
async def main():
print('Hello ...')
await asyncio.sleep(1)
print('... World!')
asyncio.run(main())
Why is main
called inside the asyncio.run()
(and in other asyncio functions like asyncio.gather()
)?
It confuses me, because in JavaScript, we do things like document.addEventListener('click', someFunction)
- we pass someFunction
, not its result.
I assume, the async function returns some callable object, but e.g. a Google search for python "what does an async function return?" gives no results.
asyncio.run expects a coroutine as argument.
Referring to the Python glossary, main
is a coroutine function which returns a coroutine.
So, main()
must be passed to asyncio.run
, not main
.