asyncio.get_event_loop() has the caracteristics of asyncio.get_running_loop(), asyncio.new_event_loop() and asyncio.set_event_loop().
asyncio.get_event_loop() deprecated since version 3.10:
Get the current event loop.
If there is no current event loop set in the current OS thread, the OS
thread is main, and set_event_loop() has not yet been called, asyncio
will create a new event loop and set it as the current one.
asyncio.get_running_loop():
Return the running event loop in the current OS thread.
asyncio.new_event_loop():
Create and return a new event loop object.
asyncio.set_event_loop():
Set loop as a current event loop for the current OS thread
For example, if running this code below:
import asyncio
async def test():
while True:
print("Test")
await asyncio.sleep(1)
async def call_test():
loop = asyncio.get_running_loop()
loop.create_task(test())
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.create_task(call_test())
loop.run_forever()
Test is printed every second:
Test
Test
Test
...
So now, we can replace asyncio.get_running_loop() with asyncio.get_event_loop() in call_test() and replace loop = asyncio.new_event_loop() and asyncio.set_event_loop(loop) with asyncio.get_event_loop() as shown below:
import asyncio
async def test():
while True:
print("Test")
await asyncio.sleep(1)
async def call_test():
loop = asyncio.get_event_loop() # Here
# loop = asyncio.get_running_loop()
loop.create_task(test())
loop = asyncio.get_event_loop() # Here
# loop = asyncio.new_event_loop()
# asyncio.set_event_loop(loop)
loop.create_task(call_test())
loop.run_forever()
Then, Test is still printed every second:
Test
Test
Test
...
So, about when to use asyncio.get_event_loop() or asyncio.get_running_loop(), you shouldn't use asyncio.get_event_loop() anytime because it is deprecated since version 3.10. So instead, you should use asyncio.get_running_loop() everytime and also asyncio.new_event_loop() and asyncio.set_event_loop(). But if you really want to use asyncio.get_event_loop(), use it to decrease code.
get_running_loopwill raise aRuntimeErroris no loop is running;get_event_loop, on the other hand, will create one.