J-qak J-qak - 4 months ago 9x
Python Question

Start async function without importing the asyncio package

Is is possible to start a function like this

async def foo():
while True:

without importing the
package (and getting the event loop)?

I am looking for a principle similar to Go's goroutines, where one can launch a coroutine with only

Edit: The reason why I'm not importing the asyncio package is simply because I think it should be possible to launch coroutine without event loop (explicit). I don't understand why async def and similar statements are part of core language (even part of syntax) and the way to launch created coroutines is available only through package.


No, you have to 'start' a coroutine by throwing into the async loop.

You can do that in two ways (without using yield or await syntax),

  • asyncio.ensure_future
  • asyncio.BaseEventLoop.create_task

So the answer to your question is no. Also as a side note, for anything to happen at all you have to start the loop. with either

  • BaseEventLoop.run_forever or
  • BaseEventLoop.run_until_complete

Hopes this helps.