35

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?

Elektito
  • 3,663
  • 7
  • 40
  • 67

1 Answers1

25

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.

Jashandeep Sohi
  • 4,503
  • 1
  • 20
  • 25
  • Sounds like I'd better use `ensure_future` then. Thanks for clearing this up. – Elektito Nov 29 '15 at 07:37
  • 1
    Unless you're writing code for Python < 3.4.4, of course ;) – Jashandeep Sohi Nov 29 '15 at 07:40
  • Ah, yes. I didn't pay attention! I _am_ using Python < 3.4.4 as it happens; 3.4.3 to be precise. – Elektito Nov 29 '15 at 07:42
  • This was counter-intuitive because it sounded like you said to use ensure_future and not create_task, so I made my research. In 2016, [Guido said the opposite](https://github.com/python/asyncio/issues/477#issuecomment-268709555). If you know you have a coroutine and you want to schedule its execution, you should just call create_task directly. create_task exists so a third party loop can return a subclass so you shouldn't call the task constructor directly. Hope that clears things up for other asyncio neophytes. – Domino Jun 08 '18 at 16:47