How the heck does async/await work in Python 3.5

Ian Kelly ian.g.kelly at gmail.com
Tue Feb 23 12:37:31 EST 2016


On Tue, Feb 23, 2016 at 9:50 AM, Sven R. Kunze <srkunze at mail.de> wrote:
> On 23.02.2016 01:48, Ian Kelly wrote:
>>
>> On Mon, Feb 22, 2016 at 3:16 PM, Sven R. Kunze <srkunze at mail.de> wrote:
>>>
>>> Is something like shown in 12:50 ( cout << tcp_reader(1000).get() )
>>> possible
>>> with asyncio? (tcp_reader would be async def)
>>
>> loop = asyncio.get_event_loop()
>> print(loop.run_until_complete(tcp_reader(1000)))
>
>
> I see. Thanks. :)
>
> How come that Python (compared to C++) needs much more boilerplate to use
> async programming? Historically, it was the other way round.

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.

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)))


More information about the Python-list mailing list