Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Python] Fix mainloop async warnings #3550

Merged
merged 1 commit into from
Oct 17, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 22 additions & 15 deletions src/fable-library-py/fable_library/async_.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,23 @@ def callback(conts: Continuations[_T]) -> None:
return from_continuations(callback)


def run_in_loop(computation: Callable[..., None]) -> Any:
"""Run a computation on the event loop.

If no event loop is running, then one is created and run.
"""

async def runner() -> None:
return computation()

try:
asyncio.get_running_loop()
except RuntimeError:
return asyncio.run(runner())
else:
return computation()


def start_with_continuations(
computation: Async[_T],
continuation: Callable[[_T], None] | None = None,
Expand All @@ -214,7 +231,10 @@ def start_with_continuations(
cancellation_token or default_cancellation_token,
)

return computation(ctx)
def runner() -> None:
computation(ctx)

run_in_loop(runner)


def start_as_task(
Expand Down Expand Up @@ -281,20 +301,7 @@ def start_immediate(
Runs an asynchronous computation, starting immediately on the
current operating system thread
"""
try:
asyncio.get_event_loop()
except RuntimeError:

async def runner() -> None:
return start_with_continuations(
computation, cancellation_token=cancellation_token
)

return asyncio.run(runner())
else:
return start_with_continuations(
computation, cancellation_token=cancellation_token
)
start_with_continuations(computation, cancellation_token=cancellation_token)


_executor: ThreadPoolExecutor | None = None
Expand Down
2 changes: 1 addition & 1 deletion src/fable-library-py/fable_library/async_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,7 @@ def protected_bind(
computation: Callable[[IAsyncContext[_T]], None],
binder: Callable[[_T], Async[_U]],
) -> Async[_U]:
def cont(ctx: IAsyncContext[_T]):
def cont(ctx: IAsyncContext[_U]) -> None:
def on_success(x: _T) -> None:
try:
binder(x)(ctx)
Expand Down
Loading