A script I am upgrading uses asyncio.get_event_loop()
, which is deprecated since Python 3.12.
Asyncio documentation recommends using asyncio.get_running_loop()
, which is considered more stable because its output is simpler and more predictable. However, get_running_loop()
requires that the loop be running, and can only be called from a coroutine or callback - which is not compatible with my function structure.
Is there another asyncio replacement to get the event loop?
Usually one will want to call just asyncio.run
- to get the asynchronous part of a program started in the current thread.
If one needs a reference to the loop before calling run
(in order, for example, to create futures and tasks from the synchronous code), it is possible to call asyncio.new_event_loop()
, followed by loop.run_until_complete()
- in the same pattern that was used with .get_event_loop()
before asyncio.run
existed.
TL;DR: asyncio.new_event_loop()
is the function you are looking for.