
On Thu, May 19, 2016 at 11:49 AM, Ilya Kulakov kulakov.ilya@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())
TL;DR `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.