Skip to content

Commit

Permalink
fix: no hard dependency on nest_asyncio, use only when needed. (#311)
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 8, 2024
1 parent 592af06 commit 558da8d
Showing 1 changed file with 25 additions and 7 deletions.
32 changes: 25 additions & 7 deletions ipyvuetify/extra/file_input.py
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,23 @@ async def read_all():
self.widget.update_stats(self.file_index, chunk_size)
await process_messages()

def has_event_loop():
try:
asyncio.get_event_loop()
return True
except RuntimeError:
return False

if has_event_loop():
# we already have an event loop in this thread, 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 +193,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 558da8d

Please sign in to comment.