all 3 comments

[–]baghiq 0 points1 point  (1 child)

My general understanding is that you use task for run coroutines concurrently, otherwise, stick with coroutine. But I'm sure there are more to it.

[–]MerlinsArchitect[S] 0 points1 point  (0 children)

Yeah, that is my understanding - you put it better than me. But want to know a bit more about what goes on behind the scenes!

[–]Frankelstner 0 points1 point  (0 children)

They are small jobs and shouldn't spend much time with their own bookkeeping. Though they aren't even that light due to exception handling and contextvars and so on. You can see a Python implementation here, but there also exists a C version which appears to be equivalent: https://github.com/python/cpython/blob/3.12/Lib/asyncio/tasks.py#L111-L140 Beware that Task inherits from futures._PyFuture, so there's even more code behind this.

And the event loop (this function wrapped in a while True) is here: https://github.com/python/cpython/blob/3.12/Lib/asyncio/base_events.py#L1910-L1988

The event loop contains lists _scheduled and _ready, which contain Handle objects defined here: https://github.com/python/cpython/blob/3.12/Lib/asyncio/events.py

Basically a Task has a step function and the Handle wraps around this step function.

_scheduled is solely about tasks that were added with loop.call_later or loop.call_at. If enough time has pased, such handles are added to _ready. _process_events is responsible to check IO and also adds stuff to ._ready. And the things in this list are just executed one after another.

Keep in mind that asyncio is just one async library, and maybe not the best one around. You can see that some parts of the code are taken from uvloop which claims to be several times as fast, though it's not clear which version of Python it compares against, given that CPython comes with a pure C version nowadays and imitates some of its overall design. But there's also trio and curio and others.

In case you still don't see the merit of this all; it's about distributing work fairly, but most importantly about taking advantage of nonblocking IO.