Skip to content

Commit

Permalink
fix: no event loop in current thread (#38)
Browse files Browse the repository at this point in the history
  • Loading branch information
BobTheBuidler authored May 31, 2023
1 parent cdc392d commit 3b77986
Showing 1 changed file with 9 additions and 2 deletions.
11 changes: 9 additions & 2 deletions a_sync/_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,13 @@
from a_sync._typing import *


def get_event_loop() -> asyncio.BaseEventLoop:
try:
return asyncio.get_event_loop()
except RuntimeError:
asyncio.set_event_loop(asyncio.new_event_loop())
return asyncio.get_event_loop()

def _validate_wrapped_fn(fn: Callable) -> None:
"""Ensures 'fn' is an appropriate function for wrapping with a_sync."""
if isinstance(fn, (AsyncPropertyDescriptor, AsyncCachedPropertyDescriptor)):
Expand All @@ -27,7 +34,7 @@ def _validate_wrapped_fn(fn: Callable) -> None:

def _await(awaitable: Awaitable[T]) -> T:
try:
return asyncio.get_event_loop().run_until_complete(awaitable)
return get_event_loop().run_until_complete(awaitable)
except RuntimeError as e:
if str(e) == "This event loop is already running":
raise RuntimeError(str(e), running_event_loop_msg)
Expand All @@ -36,5 +43,5 @@ def _await(awaitable: Awaitable[T]) -> T:
def _asyncify(func: SyncFn[P, T], executor: Executor) -> CoroFn[P, T]:
@functools.wraps(func)
async def _asyncify_wrap(*args: P.args, **kwargs: P.kwargs) -> T:
return await asyncio.get_event_loop().run_in_executor(executor, func, *args, **kwargs)
return await get_event_loop().run_in_executor(executor, func, *args, **kwargs)
return _asyncify_wrap

0 comments on commit 3b77986

Please sign in to comment.