Skip to content

Commit 837ae73

Browse files
refactor: simplify apply_nest_asyncio and ensure it is applied for the Executor
- nest_asyncio has internal checks for whether it is applied, rely on those - Ensured apply_nest_asyncio is called in the Executor class to handle nested event loops.
1 parent 0877a22 commit 837ae73

File tree

2 files changed

+16
-17
lines changed

2 files changed

+16
-17
lines changed

ragas/src/ragas/async_utils.py

Lines changed: 14 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -9,22 +9,6 @@
99
logger = logging.getLogger(__name__)
1010

1111

12-
def apply_nest_asyncio():
13-
NEST_ASYNCIO_APPLIED: bool = False
14-
if is_event_loop_running():
15-
# an event loop is running so call nested_asyncio to fix this
16-
try:
17-
import nest_asyncio
18-
except ImportError:
19-
raise ImportError(
20-
"It seems like your running this in a jupyter-like environment. Please install nest_asyncio with `pip install nest_asyncio` to make it work."
21-
)
22-
23-
if not NEST_ASYNCIO_APPLIED:
24-
nest_asyncio.apply()
25-
NEST_ASYNCIO_APPLIED = True
26-
27-
2812
def is_event_loop_running() -> bool:
2913
"""
3014
Check if an event loop is currently running.
@@ -37,6 +21,20 @@ def is_event_loop_running() -> bool:
3721
return loop.is_running()
3822

3923

24+
def apply_nest_asyncio():
25+
"""Apply nest_asyncio if an event loop is running."""
26+
if is_event_loop_running():
27+
# an event loop is running so call nested_asyncio to fix this
28+
try:
29+
import nest_asyncio
30+
except ImportError:
31+
raise ImportError(
32+
"It seems like your running this in a jupyter-like environment. Please install nest_asyncio with `pip install nest_asyncio` to make it work."
33+
)
34+
35+
nest_asyncio.apply()
36+
37+
4038
def as_completed(
4139
coroutines: t.Sequence[t.Coroutine], max_workers: int = -1
4240
) -> t.Iterator[asyncio.Future]:

ragas/src/ragas/executor.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
import numpy as np
88
from tqdm.auto import tqdm
99

10-
from ragas.async_utils import as_completed, process_futures, run
10+
from ragas.async_utils import apply_nest_asyncio, as_completed, process_futures, run
1111
from ragas.run_config import RunConfig
1212
from ragas.utils import ProgressBarManager, batched
1313

@@ -204,6 +204,7 @@ def results(self) -> t.List[t.Any]:
204204
async def _async_wrapper():
205205
return await self.aresults()
206206

207+
apply_nest_asyncio()
207208
return run(_async_wrapper)
208209

209210

0 commit comments

Comments
 (0)