Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is event_loop_policy and why is it needed in python asyncio?

The event loops documentation mentions event_loop_policy but doesn’t describe what it is and why this abstract layer is needed in detail. (the documentation even says one can customize this layer).

In addition, help(asyncio.get_event_loop_policy()) is just saying...

UNIX event loop policy with a watcher for child processes.

Then, I come to be more confused. What is watcher? What are child processes in event loop?

like image 886
SangminKim Avatar asked Feb 04 '18 03:02

SangminKim


1 Answers

Event loop policy is an object that is used to create, set or get event loops. For example, when you call asyncio.new_event_loop() it is policy who will determine concrete returned event loop's class.

Policy is needed if you for some reason would want to change default event loop type. Encapsulating logic of creating loops inside a separate replaceable (what is convenient) policy object is a strategy programming pattern.

help(asyncio.get_event_loop_policy()) gives you docs for concrete policy used in your OS, in your case for _UnixDefaultEventLoopPolicy.

By the link you can see how things implemented there, find what watcher is and read it's docs:

 class SafeChildWatcher(BaseChildWatcher):
    """'Safe' child watcher implementation.

    This implementation avoids disrupting other code spawning processes by
    polling explicitly each process in the SIGCHLD handler instead of calling
    os.waitpid(-1).

    This is a safe solution but it has a significant overhead when handling a
    big number of children (O(n) each time SIGCHLD is raised)
    """

As you can see it's pretty low-level, OS-specific stuff and you usually don't need it to use asyncio.

I think you may need to investigate policies only if you're going to write your event loops and/or policies that manages them.

like image 197
Mikhail Gerasimov Avatar answered Nov 04 '22 05:11

Mikhail Gerasimov