Skip to content
This repository has been archived by the owner on Mar 6, 2024. It is now read-only.

Commit

Permalink
In asyncio.run: Create new loop if no loop present in current thread,…
Browse files Browse the repository at this point in the history
… see #61
  • Loading branch information
erdewit committed Dec 1, 2021
1 parent cd80b74 commit 1856573
Showing 1 changed file with 8 additions and 4 deletions.
12 changes: 8 additions & 4 deletions nest_asyncio.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

def apply(loop=None):
"""Patch asyncio to make its event loop reentrant."""
loop = loop or asyncio.get_event_loop()
loop = loop or events._get_running_loop()
if not isinstance(loop, asyncio.BaseEventLoop):
raise ValueError('Can\'t patch loop of type %s' % type(loop))
if getattr(loop, '_nest_patched', None):
Expand All @@ -26,10 +26,14 @@ def _patch_asyncio():
Patch asyncio module to use pure Python tasks and futures,
use module level _current_tasks, all_tasks and patch run method.
"""
def run(coro, *, debug=False):
loop = asyncio.get_event_loop()
def run(main, *, debug=False):
loop = events._get_running_loop()
if not loop:
loop = events.new_event_loop()
events.set_event_loop(loop)
_patch_loop(loop)
loop.set_debug(debug)
task = asyncio.ensure_future(coro)
task = asyncio.ensure_future(main)
try:
return loop.run_until_complete(task)
finally:
Expand Down

0 comments on commit 1856573

Please sign in to comment.