Skip to content

Commit 18b58bf

Browse files
authored
fix: handle RuntimeError correctly in run_sync (#425)
1 parent 283b128 commit 18b58bf

File tree

2 files changed

+27
-10
lines changed

2 files changed

+27
-10
lines changed

jupyter_core/utils/__init__.py

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -151,18 +151,17 @@ def wrapped(*args: Any, **kwargs: Any) -> Any:
151151
name = threading.current_thread().name
152152
inner = coro(*args, **kwargs)
153153
try:
154-
# If a loop is currently running in this thread,
155-
# use a task runner.
156154
asyncio.get_running_loop()
157-
if name not in _runner_map:
158-
_runner_map[name] = _TaskRunner()
159-
return _runner_map[name].run(inner)
160155
except RuntimeError:
161-
pass
162-
163-
# Run the loop for this thread.
164-
loop = ensure_event_loop()
165-
return loop.run_until_complete(inner)
156+
# No loop running, run the loop for this thread.
157+
loop = ensure_event_loop()
158+
return loop.run_until_complete(inner)
159+
160+
# Loop is currently running in this thread,
161+
# use a task runner.
162+
if name not in _runner_map:
163+
_runner_map[name] = _TaskRunner()
164+
return _runner_map[name].run(inner)
166165

167166
wrapped.__doc__ = coro.__doc__
168167
return wrapped

tests/test_utils.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,24 @@ async def foo():
5656

5757
asyncio.run(foo())
5858

59+
error_msg = "__foo__"
60+
61+
async def error():
62+
raise RuntimeError(error_msg)
63+
64+
error_sync = run_sync(error)
65+
66+
def test_error_sync():
67+
with pytest.raises(RuntimeError, match=error_msg):
68+
error_sync()
69+
70+
test_error_sync()
71+
72+
async def with_running_loop():
73+
test_error_sync()
74+
75+
asyncio.run(with_running_loop())
76+
5977

6078
def test_ensure_async():
6179
async def main():

0 commit comments

Comments
 (0)