Skip to content

Commit

Permalink
fix: no hard dependency on nest_asyncio, use only when needed.
Browse files Browse the repository at this point in the history
Only when we have a current event loop do we need nest_asyncio to be
used and installed. In case where readinto is called from a thread
(this is something we do in solara) which does not have an event loop
yet, we should not need nest_asyncio.

When needed, and not installed, we raise an error with an informative
installation instruction.
  • Loading branch information
maartenbreddels committed Apr 5, 2024
1 parent 778deaa commit b0e8c95
Showing 1 changed file with 23 additions and 7 deletions.
30 changes: 23 additions & 7 deletions ipyvuetify/extra/file_input.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,14 @@
import sys

import IPython
import nest_asyncio

try:
import nest_asyncio

has_nest_asyncio = True
except ModuleNotFoundError:
has_nest_asyncio = False

import traitlets

import ipyvuetify as v
Expand Down Expand Up @@ -140,6 +147,21 @@ async def read_all():
self.widget.update_stats(self.file_index, chunk_size)
await process_messages()

try:
# robust way to check if we already have an event loop
asyncio.get_event_loop()
except RuntimeError:
pass
else:
# we already have an event loop, so to be able to call asyncio.run(...)
# while also receiving messages from the frontend, we need to use nest_asyncio
if not has_nest_asyncio:
raise RuntimeError(
"nest_asyncio is required for FileInput when an event loop is already running in the current thread, "
"please run 'pip install nest_asyncio'."
)
else:
nest_asyncio.apply()
asyncio.run(read_all())
return size

Expand Down Expand Up @@ -169,12 +191,6 @@ def __init__(self, **kwargs):
self.stats = []
super().__init__(**kwargs)

if not hasattr(IPython.get_ipython(), "kernel"):
return
kernel = IPython.get_ipython().kernel
if kernel.implementation == "ipython":
nest_asyncio.apply()

@traitlets.observe("file_info")
def _file_info_changed(self, _):
self.version += 1
Expand Down

0 comments on commit b0e8c95

Please sign in to comment.