Battery_Al
Battery_Al

Reputation: 809

What are the use cases for `asyncio.new_event_loop`?

I realize new_event_loop is called by get_event_loop if a loop doesn't already exist - I'm wondering if there are reasons that new_event_loop might be called in addition to or instead of the typical get_event_loop.

It seems like new_event_loop could be used to:

  1. Have multiple event loops in a single application.
  2. Create a new event loop after one was killed.

I can't come up with a good reason for doing either of these though. Have you guys ever encountered a use case for explicitly calling new_event_loop?

Upvotes: 2

Views: 2518

Answers (1)

Charnel
Charnel

Reputation: 4432

Explicit event loop creation is mostly used in two cases:

  • You need to run the event loop out of the main thread. Here what doc's saying:

The default policy defines context as the current thread, and manages an event loop per thread that interacts with asyncio. If the current thread doesn’t already have an event loop associated with it, the default policy’s get_event_loop() method creates one when called from the main thread, but raises RuntimeError otherwise

  • You want to use custom policy in single application (for example support different implementations for different platforms withing the same app). You can read about policies here.

Basically, policy is needed if you want to change default event loop type.

Upvotes: 4

Related Questions