From 9d46de93f251f717912dd6055ef79b68e80dec26 Mon Sep 17 00:00:00 2001 From: Ewald de Wit Date: Thu, 27 Jul 2023 19:56:02 +0200 Subject: [PATCH] Patch event loop policy to always return a patched loop --- nest_asyncio.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/nest_asyncio.py b/nest_asyncio.py index f8123e3..21cf7ca 100644 --- a/nest_asyncio.py +++ b/nest_asyncio.py @@ -12,6 +12,7 @@ def apply(loop=None): """Patch asyncio to make its event loop reentrant.""" _patch_asyncio() + _patch_policy() _patch_task() _patch_tornado() @@ -63,6 +64,20 @@ def _get_event_loop(stacklevel=3): asyncio._nest_patched = True +def _patch_policy(): + """Patch the policy to always return a patched loop.""" + + def get_event_loop(self): + if self._local._loop is None: + loop = self.new_event_loop() + _patch_loop(loop) + self.set_event_loop(loop) + return self._local._loop + + policy = events.get_event_loop_policy() + policy.__class__.get_event_loop = get_event_loop + + def _patch_loop(loop): """Patch loop to make it reentrant."""