Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between loop.create_task, asyncio.async/ensure_future and Task?

I'm a little bit confused by some asyncio functions. I see there is BaseEventLoop.create_task(coro) function to schedule a co-routine. The documentation for create_task says its a new function and for compatibility we should use asyncio.async(coro) which by referring to docs again I see is an alias for asyncio.ensure_future(coro) which again schedules the execution of a co-routine.

Meanwhile, I've been using Task(coro) for scheduling co-routine execution and that too seems to be working fine. so, what's the difference between all these?

like image 956
Elektito Avatar asked Nov 29 '15 06:11

Elektito


People also ask

What does Asyncio Ensure_future do?

tl;dr ensure_future let's us execute a coroutine in the background, without explicitly waiting for it to finish. If we need, we can wait for it later or poll for result. In other words, this is a way of executing code in asyncio without await.

What is Asyncio Create_task?

It's an asyncio construct that tracks execution of a coroutine in a concrete event loop. When you call create_task , you submit a coroutine for execution and receive back a handle. You can await this handle when you actually need the result, or you can never await it, if you don't care about the result.

What are Asyncio tasks?

Tasks within Asyncio are responsible for the execution of coroutines within an event loop. These tasks can only run in one event loop at one time and in order to achieve parallel execution you would have to run multiple event loops over multiple threads.

Which function is used to run Awaitables concurrently in Asyncio?

gather() method - It runs awaitable objects (objects which have await keyword) concurrently.


1 Answers

As you've noticed, they all do the same thing.

asyncio.async had to be replaced with asyncio.ensure_future because in Python >= 3.5, async has been made a keyword[1].

create_task's raison d'etre[2]:

Third-party event loops can use their own subclass of Task for interoperability. In this case, the result type is a subclass of Task.

And this also means you should not create a Task directly, because different event loops might have different ways of creating a "Task".

Edit

Another important difference is that in addition to accepting coroutines, ensure_future also accepts any awaitable object; create_task on the other hand just accepts coroutines.

like image 183
Jashandeep Sohi Avatar answered Oct 05 '22 21:10

Jashandeep Sohi