8000 bpo-31950: Improve event loop policy doc · python/cpython@8f0134b · GitHub
[go: up one dir, main page]

Skip to content

Commit 8f0134b

Browse files
committed
bpo-31950: Improve event loop policy doc
1 parent 088929c commit 8f0134b

File tree

1 file changed

+30
-3
lines changed

1 file changed

+30
-3
lines changed

Doc/library/asyncio-eventloops.rst

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -148,10 +148,9 @@ process based on the calling context. A policy is an object implementing the
148148
:class:`AbstractEventLoopPolicy` interface.
149149

150150
For most users of :mod:`asyncio`, policies never have to be dealt with
151-
explicitly, since the default global policy is sufficient.
151+
explicitly, since the default global policy is sufficient (see below).
152152

153-
The default policy defines context as the current thread, and manages an event
154-
loop per thread that interacts with :mod:`asyncio`. The module-level functions
153+
The module-level functions
155154
:func:`get_event_loop` and :func:`set_event_loop` provide convenient access to
156155
event loops managed by the default policy.
157156

@@ -189,6 +188,13 @@ An event loop policy must implement the following interface:
189188
context, :meth:`set_event_loop` must be called explicitly.
190189

191190

191+
The default policy defines context as the current thread, and manages an event
192+
loop per thread that interacts with :mod:`asyncio`. If the current thread
193+
doesn't already have an event loop associated with it, the default policy's
194+
:meth:`~AbstractEventLoopPolicy.get_event_loop` method creates one when
195+
called from the main thread, but raises :exc:`RuntimeError` otherwise.
196+
197+
192198
Access to the global loop policy
193199
--------------------------------
194200

@@ -200,3 +206,24 @@ Access to the global loop policy
200206

201207
Set the current event loop policy. If *policy* is ``None``, the default
202208
policy is restored.
209+
210+
211+
Customizing the event loop policy
212+
---------------------------------
213+
214+
To implement a new event loop policy, it is recommended you subclass the
215+
concrete default event loop policy :class:`DefaultEventLoopPolicy`
216+
and override the methods for which you want to change behavior, for example::
217+
218+
class MyEventLoopPolicy(asyncio.DefaultEventLoopPolicy):
219+
220+
def get_event_loop(self):
221+
"""Get the event loop.
222+
223+
This may be None or an instance of EventLoop.
224+
"""
225+
loop = super().get_event_loop()
226+
# Do something with loop ...
227+
return loop
228+
229+
asyncio.set_event_loop_policy(MyEventLoopPolicy())

0 commit comments

Comments
 (0)
0