Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between using call_soon() and ensure_future()

I'm new to this framework and am trying to understand the difference/benefits of using one over the other

I could use a non-async function that is not a co-routine to do

def while_naughty():
    print("naughty")

loop.call_soon(self.while_naughty)

or

async def naughty():
    print("naughty")

task = asyncio.ensure_future(naughty())

I know that ensure_future takes a co-routine as parameter, I hope to learn about situations where it is more advantageous to use call_soon() over ensure_future().

like image 971
laycat Avatar asked Oct 25 '25 08:10

laycat


1 Answers

The non-coroutine version will never act cooperatively. You can't await on anything else in that function, and because of the way you invoked it, you can't return a result to the caller.

loop.call_soon() is specifically meant to be used for callbacks, which usually are very simple functions used to hook into events (job done, exception was raised in future, etc.), and they are not expected to cooperate.

Callbacks are also not expected to return anything; they are fire-and-forget routines, trusted to not lock up the whole system by running anything heavy or blocking. call_soon() returns a Handle() instance that only lets you cancel it again (a no-op if it already has been executed). The callbacks are executed next time the event loop checks the callback queue, at which point they (hopefully briefly) block any other work from being done*.

Note that asyncio.ensure_future() only creates a Future() instance, the task is not actually started! But if you did start it (with, say, loop.run_until_complete()), you get more control. You now have proper coroutine, it can await on other coroutines. Awaiting on other coroutines lets the event loop switch to other coroutines that are ready to continue, ensuring your CPU is busy doing actual work when there is work to be done. And your coroutine can return actual results to the caller too.

Use whichever one better fits your use-cases. In a large application, you'll likely use both.


* When you run in debug mode you are told when callbacks take too long, so you can debug these.

like image 173
Martijn Pieters Avatar answered Oct 26 '25 22:10

Martijn Pieters