[Python-ideas] Add ability to get current event loop within asyncio coroutine

Guido van Rossum guido at python.org
Fri May 20 12:22:39 EDT 2016

OK, I finally see the point. There are legitimate situations where
get_event_loop() returns None (this is how most of asyncio's tests are
running). So we want a separate function, e.g.
get_current_event_loop(). Send a PR to the GitHub project.

On Fri, May 20, 2016 at 2:02 AM, Vincent Michel <vxgmichel at gmail.com> wrote:
> On Thu, May 19, 2016 at 11:49 AM, Ilya Kulakov <kulakov.ilya at gmail.com>
> wrote:
>> I think Python would benefit from providing either a new method (e.g.
>> `asyncio.current_event_loop`) or modifying `asyncio.get_event_loop`
>> to return current event loop when called from a coroutine. It should, in
>> my
>> opinion, reduce necessity of passing event loop
>> between coroutines in application's code as it is done in asyncio itself
>> and
>> 3rd party libraries (like aiohttp).
> I was about to make the same proposal. I can add two practical arguments in
> favor.
> First, some coroutines could be simplified. For instance, asyncio.sleep
> takes an optional loop argument, defaulting to get_event_loop(). But
> get_event_loop is called inside the coroutine, and therefore inside a
> running event loop. This loop is actually the only valid choice, and using
> anything else should raise an exception. If get_event_loop is guaranteed to
> return the current running loop, then there is no reason to pass it as an
> argument to asyncio.sleep. Other coroutines could benefit from that,
> including wait and wait_for.
> It would also help for queues, locks and other task functions (gather,
> shield, as_completed, etc.). Here the loop argument is still useful, in case
> those objects are declared outside their event loop. However, it would be
> really convenient to assume loop=None always works as expected if the object
> is created inside a coroutine. In many cases, libraries tend to forward the
> loop argument from coroutine to coroutine, just in case someone writes:
> loop = asyncio.new_event_loop()
> loop.run_until_complete(my_coro(loop=loop))
> instead of:
> loop = asyncio.new_event_loop()
> asyncio.set_event_loop(loop)
> loop.run_until_complete(my_coro())
> `async def coro(*, loop=None)` doesn't really make sense, and could be
> discouraged if get_event_loop was guaranteed to return the running event
> loop when called inside a coroutine.
> _______________________________________________
> 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)

More information about the Python-ideas mailing list