When should we use asyncio.get_running_loop() vs asyncio.get_event_loop()?

Viewed 4195

I have seen running a blocking code using

loop = asyncio.get_running_loop()
await loop.run_in_executor(None, blockingfunc)

And

loop = asyncio.get_event_loop()
await loop.run_in_executor(None, blockingfunc)

When should we use asyncio.get_running_loop() vs asyncio.get_event_loop()?

1 Answers

In accordance with the official documentation, both the get_running_loop and get_event_loop are used to actually get an active loop, with the difference that the latter get_event_loop has more complex behaviour, thus get_running_loop can be used widely in the applications, where the existance of the loop is not questionable.

Moreover, in the documentation it is suggested to used run method to obtain an event loop (available starting from the Python 3.7 version), e.g.

async def main():
    await asyncio.sleep(1)
    print('hello')

asyncio.run(main())   

instead of:

async def main():
    await asyncio.sleep(1)
    print('hello')
        
loop = asyncio.get_event_loop()
task = loop.create_task(main)
loop.run_forever()

Please note, that the run method solution can work weirdly in Jupyter Notebook.

Related