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

fix: no hard dependency on nest_asyncio, use only when needed. #311

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
32 changes: 25 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,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