18.5.2.Event loops¶
Source code:Lib/asyncio/events.py
18.5.2.1.Event loop functions¶
The following functions are convenient shortcuts to accessing the methods of theglobal policy. Note that this provides access to the default policy, unless analternative policy was set by callingset_event_loop_policy() earlier inthe execution of the process.
asyncio.get_event_loop()¶Equivalent to calling
get_event_loop_policy().get_event_loop().
asyncio.set_event_loop(loop)¶Equivalent to calling
get_event_loop_policy().set_event_loop(loop).
asyncio.new_event_loop()¶Equivalent to calling
get_event_loop_policy().new_event_loop().
18.5.2.2.Available event loops¶
asyncio currently provides two implementations of event loops:SelectorEventLoop andProactorEventLoop.
- class
asyncio.SelectorEventLoop¶ Event loop based on the
selectorsmodule. Subclass ofAbstractEventLoop.Use the most efficient selector available on the platform.
On Windows, only sockets are supported (ex: pipes are not supported):see theMSDN documentation of select.
- class
asyncio.ProactorEventLoop¶ Proactor event loop for Windows using “I/O Completion Ports” aka IOCP.Subclass of
AbstractEventLoop.Availability: Windows.
Example to use aProactorEventLoop on Windows:
importasyncio,sysifsys.platform=='win32':loop=asyncio.ProactorEventLoop()asyncio.set_event_loop(loop)
18.5.2.3.Platform support¶
Theasyncio module has been designed to be portable, but each platformstill has subtle differences and may not support allasyncio features.
18.5.2.3.1.Windows¶
Common limits of Windows event loops:
create_unix_connection()andcreate_unix_server()are not supported: the socketfamilysocket.AF_UNIXis specific to UNIXadd_signal_handler()andremove_signal_handler()are not supportedEventLoopPolicy.set_child_watcher()is not supported.ProactorEventLoopsupports subprocesses. It has only oneimplementation to watch child processes, there is no need to configure it.
SelectorEventLoop specific limits:
SelectSelectoris used which only supports socketsand is limited to 512 sockets.add_reader()andadd_writer()onlyaccept file descriptors of socketsPipes are not supported(ex:
connect_read_pipe(),connect_write_pipe())Subprocesses are not supported(ex:
subprocess_exec(),subprocess_shell())
ProactorEventLoop specific limits:
create_datagram_endpoint()(UDP) is not supportedadd_reader()andadd_writer()arenot supported
The resolution of the monotonic clock on Windows is usually around 15.6 msec.The best resolution is 0.5 msec. The resolution depends on the hardware(availability ofHPET) and on the Windowsconfiguration. Seeasyncio delayed calls.
Changed in version 3.5:ProactorEventLoop now supports SSL.
18.5.2.3.2.Mac OS X¶
Character devices like PTY are only well supported since Mavericks (Mac OS10.9). They are not supported at all on Mac OS 10.5 and older.
On Mac OS 10.6, 10.7 and 10.8, the default event loop isSelectorEventLoop which usesselectors.KqueueSelector.selectors.KqueueSelector does not support character devices on theseversions. TheSelectorEventLoop can be used withSelectSelector orPollSelector tosupport character devices on these versions of Mac OS X. Example:
importasyncioimportselectorsselector=selectors.SelectSelector()loop=asyncio.SelectorEventLoop(selector)asyncio.set_event_loop(loop)
18.5.2.4.Event loop policies and the default policy¶
Event loop management is abstracted with apolicy pattern, to provide maximalflexibility for custom platforms and frameworks. Throughout the execution of aprocess, a single global policy object manages the event loops available to theprocess based on the calling context. A policy is an object implementing theAbstractEventLoopPolicy interface.
For most users ofasyncio, policies never have to be dealt withexplicitly, since the default global policy is sufficient (see below).
The module-level functionsget_event_loop() andset_event_loop() provide convenient access toevent loops managed by the default policy.
18.5.2.5.Event loop policy interface¶
An event loop policy must implement the following interface:
- class
asyncio.AbstractEventLoopPolicy¶ Event loop policy.
get_event_loop()¶Get the event loop for the current context.
Returns an event loop object implementing the
AbstractEventLoopinterface. In case called from coroutine, it returns the currentlyrunning event loop.Raises an exception in case no event loop has been set for the currentcontext and the current policy does not specify to create one. It mustnever return
None.Changed in version 3.6.
set_event_loop(loop)¶Set the event loop for the current context toloop.
new_event_loop()¶Create and return a new event loop object according to this policy’srules.
If there’s need to set this loop as the event loop for the currentcontext,
set_event_loop()must be called explicitly.
The default policy defines context as the current thread, and manages an eventloop per thread that interacts withasyncio. If the current threaddoesn’t already have an event loop associated with it, the default policy’sget_event_loop() method creates one whencalled from the main thread, but raisesRuntimeError otherwise.
18.5.2.6.Access to the global loop policy¶
asyncio.get_event_loop_policy()¶Get the current event loop policy.
asyncio.set_event_loop_policy(policy)¶Set the current event loop policy. Ifpolicy is
None, the defaultpolicy is restored.
18.5.2.7.Customizing the event loop policy¶
To implement a new event loop policy, it is recommended you subclass theconcrete default event loop policyDefaultEventLoopPolicyand override the methods for which you want to change behavior, for example:
classMyEventLoopPolicy(asyncio.DefaultEventLoopPolicy):defget_event_loop(self):"""Get the event loop. This may be None or an instance of EventLoop. """loop=super().get_event_loop()# Do something with loop ...returnloopasyncio.set_event_loop_policy(MyEventLoopPolicy())
