How to get currently running EventLoop in python36?

Viewed 1421

I know that in python37 we have a new api asyncio.get_running_loop(), which is easy to use, let us do not need to pass eventloop explicitly when we call a coroutine.

I'm wondering if there's any approach we can use to get the same effect in python36?

# which allows us coding conveniently with this api:
import asyncio

async def test():
    print("hello world !")

async def main():
    loop = asyncio.get_running_loop()
    loop.create_task(test())

asyncio.run(main())
1 Answers

In Python 3.6 you can use asyncio.get_event_loop() for equivalent effect.

According to the documentation, it is equivalent to calling get_event_loop_policy().get_event_loop(), which is in turn documented to return "the currently running event loop" when called from a coroutine.

In other words, when invoked from a coroutine (or from a function invoked by a coroutine), there is no difference between get_event_loop and get_running_loop, both will return the running loop. It is only when no loop is running that get_event_loop() will keep returning the loop associated with the current thread, while get_running_loop() will raise an exception. As long as you are careful to call get_event_loop() while a loop is actually running, it will be equivalent to get_running_loop().

Note that get_event_loop returning the running loop when called from a coroutine is new to Python 3.6 and 3.5.3. Prior to those versions, get_event_loop would always return the event loop associated with the current thread, which could be a different loop from the one that is actually running. This made get_event_loop() fundamentally unreliable and is the reason why old asyncio code would pass the loop argument everywhere. More details here.

Related