How the heck does async/await work in Python 3.5

Sven R. Kunze srkunze at mail.de
Tue Feb 23 14:42:49 EST 2016


On 23.02.2016 18:37, Ian Kelly wrote:
> It's not entirely clear to me what the C++ is actually doing. With
> Python we have an explicit event loop that has to be started to manage
> resuming the coroutines. Since it's explicit, you could easily drop in
> a different event loop, such as Tornado or curio, if desired. If your
> coroutine never awaits anything that isn't already done then
> technically you don't need an event loop, but at that point you might
> as well be using ordinary functions.

I don't think taking the shortcut to ordinary functions will work on the 
big scale.

I certainly agree that asynchronous operations can/should? be the very 
core of everything (files, sockets, timers, etc.); just as Microsoft is 
pushing with their Windows API. Chaining async ops together just works 
now with async/await in Python as well. However, in the end of the 
chaining there'll always be synchronous code that e.g. initializes the 
event loop. Real world code works the same.

Imagine, in some near/distant future, Python might have all its core 
components (like reading a file, etc. etc.) converted to async. It would 
be great for many larger applications if there one could introduce async 
gently. So, laying out an async foundation (the building blocks) but the 
wiring synchronous operations still work as they should. Once, the team 
decides they want to leverage the async potential in their code (as the 
building blocks COULD be executed concurrently), they will then be able 
to replace the synchronous wires with an event loop.

So, I see quite some potential here.

> The C++ on the other hand seems to be doing something implicit at the
> compiler level to make everything happen automatically inside the
> future.get() call, but I don't know what that is.
>
> You could wrap up the boilerplate in Python if you like:
>
> def get(coro, loop=None):
>      if loop is None:
>          loop = asyncio.get_event_loop()
>      return loop.run_until_complete(coro)
>
> print(get(tcp_reader(1000)))

As usual. :)

Best,
Sven



More information about the Python-list mailing list