Snippets Python / Asyncio Event Loop

Asyncio Event Loop

By Marcelo Fernandes Sep 10, 2017

Event Loop

The event loop is the place where most of the magic happens in asyncio

Event Loop Functions

The following functions are convenient shortcuts to accessing the methods of the global policy. Note that this provides access to the default policy, unless an alternative policy was set by calling set_event_loop_policy() earlier in the execution of the process




Available event loops

asyncio currently provides two implementations of event loops: SelectorEventLoop and ProactorEventLoop.


Event loop based on the selectors module (allows high-level and efficient I/O multiplexing). Subclass of AbstractEventLoop
Uses the most efficient selector available on the platform
On windows only sockets are supported.


Proactor event loop for windows using IOCP.

Event loop policy and the default policy.

Event loop management is abstracted with a policy pattern, to provide maximal flexibility for custom platforms and frameworks. Throughout the execution of a process, a single global policy object manages the event loops available to the process based on the calling context.
A policy is an object implementing the AbstractEventLoopPolicy interface.
For most users of asyncio, policies never have to be dealt with explicitly, since the default global policy is sufficient.
The default policy defines context as the current thread, and manages an event loop per thread that interacts with asyncio. The module-level functions get_event_loop() and set_event_loop() provide convenient access to event loops managed by the default policy

Event loop policy interface

An event loop policy should implement the following interface:



get the event loop for the current context. Should implement the AbstractEventLoop interface.


Set the event loop for the current context to loop.


Create and return a new event loop object according to this policy’s rules.

Access to the global loop policy


Get the current event loop policy.


Set the current event loop policy. If policy is None, the default policy is restored.



link 1