Skip to content

Commit d045d77

Browse files
committed
Refactor: extract _get_or_create_event_loop helper function
1 parent ab86b6c commit d045d77

File tree

1 file changed

+17
-13
lines changed

1 file changed

+17
-13
lines changed

adaptive/runner.py

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -626,18 +626,7 @@ def __init__(
626626
raise_if_retries_exceeded=raise_if_retries_exceeded,
627627
allow_running_forever=True,
628628
)
629-
if ioloop is not None:
630-
self.ioloop = ioloop
631-
else:
632-
try:
633-
self.ioloop = asyncio.get_running_loop()
634-
except RuntimeError:
635-
# No running event loop exists (e.g., running outside of async context).
636-
# Create a new event loop. This is needed for Python 3.10+ where
637-
# asyncio.get_event_loop() is deprecated when no loop is running,
638-
# and Python 3.14+ where it raises RuntimeError.
639-
self.ioloop = asyncio.new_event_loop()
640-
asyncio.set_event_loop(self.ioloop)
629+
self.ioloop = ioloop if ioloop is not None else _get_or_create_event_loop()
641630

642631
# When the learned function is 'async def', we run it
643632
# directly on the event loop, and not in the executor.
@@ -998,7 +987,22 @@ def replay_log(
998987
getattr(learner, method)(*args)
999988

1000989

1001-
# -- Internal executor-related, things
990+
# -- Internal executor-related things
991+
992+
993+
def _get_or_create_event_loop() -> asyncio.AbstractEventLoop:
994+
"""Get the running event loop or create a new one.
995+
996+
In Python 3.10+, asyncio.get_event_loop() is deprecated when no loop is running.
997+
In Python 3.14+, it raises RuntimeError instead of creating a new loop.
998+
This function provides a compatible way to get or create an event loop.
999+
"""
1000+
try:
1001+
return asyncio.get_running_loop()
1002+
except RuntimeError:
1003+
loop = asyncio.new_event_loop()
1004+
asyncio.set_event_loop(loop)
1005+
return loop
10021006

10031007

10041008
def _ensure_executor(executor: ExecutorTypes | None) -> concurrent.Executor:

0 commit comments

Comments
 (0)