Skip to content

Commit

Permalink
Merge pull request curveresearch#61 from curveresearch/notebook-fix
Browse files Browse the repository at this point in the history
Notebook fix
  • Loading branch information
nagakingg authored Nov 9, 2022
2 parents 5f474af + 7ab1b28 commit e55d08a
Showing 1 changed file with 29 additions and 1 deletion.
30 changes: 29 additions & 1 deletion curvesim/network/utils.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import asyncio
import functools
from concurrent.futures import ThreadPoolExecutor

from gmpy2 import mpz

Expand All @@ -24,6 +26,19 @@ def compute_D(xp, A):
return D


# "extra" event loop for special but important use-cases,
# such as running inside a Jupyter Notebook, which already
# runs an event loop for "convenient" await syntax.
_loop = None


def _setupExtraEventLoop():
"""Sets up the extra event loop for scheduling."""
global _loop
_loop = asyncio.new_event_loop()
ThreadPoolExecutor().submit(_loop.run_forever)


def sync(func):
"""
Returns a sync version of an async function.
Expand All @@ -39,9 +54,22 @@ def sync(func):
Sync version of the async function.
"""

@functools.wraps(func)
def inner(*args, event_loop=None, **kwargs):
loop = event_loop or asyncio.get_event_loop()
res = loop.run_until_complete(func(*args, **kwargs))
coro = func(*args, **kwargs)
if loop.is_running():
# If for some reason, we are trying to make async code
# synchronous inside a running event loop, we are
# probably in something like a Jupyter notebook.
if not _loop:
_setupExtraEventLoop()
future = asyncio.run_coroutine_threadsafe(coro, _loop)
res = future.result()

else:
res = loop.run_until_complete(coro)

return res

return inner

0 comments on commit e55d08a

Please sign in to comment.