Skip to content

Commit dc310ba

Browse files
committed
Refactor to get_event_loop_and_check_if_loop_is_running()
1 parent 09e661b commit dc310ba

File tree

2 files changed

+17
-9
lines changed

2 files changed

+17
-9
lines changed

src/omnipy/compute/mixins/auto_async.py

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
import asyncio
2-
from asyncio import AbstractEventLoop, get_event_loop
32
from inspect import iscoroutinefunction
43
from typing import Callable, cast, Coroutine
54

65
from omnipy.api.protocols.private.compute.job import IsJobBase, IsPlainFuncArgJobBase
6+
from omnipy.util.helpers import get_event_loop_and_check_if_loop_is_running
77

88

99
class AutoAsyncJobBaseMixin:
@@ -27,15 +27,9 @@ def _call_job(self, *args: object, **kwargs: object) -> object:
2727
job_func_is_coroutine: bool = iscoroutinefunction(job_func)
2828
super_call_job_func = cast(Callable[..., Coroutine], super_as_job_base._call_job)
2929

30-
loop_is_running: bool
31-
try:
32-
loop_is_running = get_event_loop().is_running()
33-
except RuntimeError:
34-
loop_is_running = False
35-
30+
loop, loop_is_running = get_event_loop_and_check_if_loop_is_running()
3631
if self.auto_async and job_func_is_coroutine and not self_as_job_base.in_flow_context:
37-
if loop_is_running:
38-
loop: AbstractEventLoop = get_event_loop()
32+
if loop and loop_is_running:
3933
res: object = loop.create_task(super_call_job_func(*args, **kwargs))
4034
else:
4135
res = asyncio.run(super_call_job_func(*args, **kwargs))

src/omnipy/util/helpers.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import asyncio
12
from collections import defaultdict, UserDict
23
from collections.abc import Hashable, Iterable
34
from copy import copy, deepcopy
@@ -796,3 +797,16 @@ def called_from_omnipy_tests() -> bool:
796797
and 'omnipy/tests' in module.__file__:
797798
return True
798799
return False
800+
801+
802+
def get_event_loop_and_check_if_loop_is_running() -> tuple[asyncio.AbstractEventLoop | None, bool]:
803+
loop_is_running: bool
804+
loop: asyncio.AbstractEventLoop | None = None
805+
806+
try:
807+
loop = asyncio.get_event_loop()
808+
loop_is_running = loop.is_running()
809+
except RuntimeError:
810+
loop_is_running = False
811+
812+
return loop, loop_is_running

0 commit comments

Comments
 (0)