asyncio: What is the difference between tasks, futures, and coroutines?

Terry Reedy tjreedy at udel.edu
Tue May 5 13:15:37 EDT 2015


On 5/5/2015 11:22 AM, Paul Moore wrote:
> I'm working my way through the asyncio documentation. I have got to
> the "Tasks and coroutines" section, but I'm frankly confused as to
> the difference between the various things described in that section:
> coroutines, tasks, and futures.
>
> I think can understand a coroutine. Correct me if I'm wrong, but it's
> roughly "something that you can run which can suspend itself".

The simple answer is that a coroutine within asyncio is a generator used 
as a (semi)coroutine rather than merely as an iterator.  IE, the send, 
throw, and close methods are used.  I believe PEP 492 will change that 
definition (for Python) to any object with with those methods.

However, if an asyncio coroutine is the result of the coroutine 
decorator, the situation is more complex, as the result is either a 
generator function, a coro function that can wrap any function, or a 
debug wrapper.  Details in asyncio/coroutine.py.

> I concede that I've not read the rest of the asyncio documentation in
> much detail yet, and I'm skipping everything to do with IO (I want to
> understand the "async" bit for now, not so much the "IO" side). But I
> don't really want to dive into the details while I am this hazy on
> the basic concepts.

You might try reading the Python code for the task and future classes.
asyncio/futures.py, asyncio/tasks.py

-- 
Terry Jan Reedy




More information about the Python-list mailing list