[Python-ideas] Built-in function to run coroutines

Guido van Rossum guido at python.org
Sat Nov 12 16:24:20 EST 2016


I think there's a plan to add a run() function to asyncio, which would be
something akin to

def run(coro):
    return get_event_loop().run_until_complete(coro)

(but perhaps with better cleanup).

Then you could start with `from asyncio import run` and from then on you'd
have your handy little function. When using standard Python you can even
put such handy imports in your $PYTHONSTARTUP file. Presumably with Jupyter
there are other, more powerful mechanisms.

--Guido

On Sat, Nov 12, 2016 at 12:45 PM, Andrew Svetlov <andrew.svetlov at gmail.com>
wrote:

> On other hand having builtin for making toy examples in interactive mode
> looks very redundant.
>
> On Sat, Nov 12, 2016 at 10:38 PM Ivan Levkivskyi <levkivskyi at gmail.com>
> wrote:
>
>> Hi,
>>
>> async/await syntax is a very nice recent feature, but there is something
>> that I miss for coroutines defined with async def, as compared to
>> generators. Coroutines represent an interesting mental model that goes
>> beyond only asynchronous IO, so that I play with them in REPL often. But
>> there is no built-in function to actually run a coroutine, so that
>> typically I use something like:
>>
>> >>> def run(coro):
>> ...     try:
>> ...         coro.send(None)
>> ...     except StopIteration as e:
>> ...         return e.value
>>
>> >>> async def f():
>> ...     return 42
>>
>> >>> run(f())
>> 42
>>
>> There is a simple yet useful function for interactive play with
>> generators - ``next``, but not for coroutines. There is an option to do:
>>
>> >>> import asyncio
>> >>> loop = asyncio.get_event_loop()
>> >>> loop.run_until_complete(f())
>> 42
>>
>> But this feels a bit redundant for an interactive play. I would propose
>> to add something like an above described ``run`` function to built-ins.
>>
>> Yes, I know, there is a very high bar for adding a built-in function, but
>> I believe such a function will help to promote async/await to a wider
>> community (especially to novices).
>>
>> --
>> Ivan
>>
>>
>> _______________________________________________
>> Python-ideas mailing list
>> Python-ideas at python.org
>> https://mail.python.org/mailman/listinfo/python-ideas
>> Code of Conduct: http://python.org/psf/codeofconduct/
>
> --
> Thanks,
> Andrew Svetlov
>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>



-- 
--Guido van Rossum (python.org/~guido)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20161112/a19cc397/attachment.html>


More information about the Python-ideas mailing list