Skip to content

Commit 70f7a66

Browse files
author
Guillermo Rodriguez
committed
Added a helpful error message if an async function is passed to trio.to_thread_run_sync
1 parent 08fca2a commit 70f7a66

File tree

3 files changed

+21
-1
lines changed

3 files changed

+21
-1
lines changed

newsfragments/1573.bugfix.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Added a helpful error message if an async function is passed to `trio.to_thread_run_sync`.

trio/_threads.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,17 @@ def do_release_then_return_result():
179179
def worker_fn():
180180
TOKEN_LOCAL.token = current_trio_token
181181
try:
182-
return sync_fn(*args)
182+
ret = sync_fn(*args)
183+
184+
if inspect.iscoroutine(ret):
185+
# Manually close coroutine to avoid RuntimeWarnings
186+
ret.close()
187+
raise TypeError(
188+
"Trio expected a sync function, but {!r} appears to be "
189+
"asynchronous".format(getattr(sync_fn, "__qualname__", sync_fn))
190+
)
191+
192+
return ret
183193
finally:
184194
del TOKEN_LOCAL.token
185195

trio/tests/test_threads.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -457,6 +457,15 @@ def thread_fn():
457457
assert callee_token == caller_token
458458

459459

460+
async def test_trio_to_thread_run_sync():
461+
# Test correct error when passed async function
462+
async def async_fn(): # pragma: no cover
463+
pass
464+
465+
with pytest.raises(TypeError, match="expected a sync function"):
466+
await to_thread_run_sync(async_fn)
467+
468+
460469
async def test_trio_from_thread_run_sync():
461470
# Test that to_thread_run_sync correctly "hands off" the trio token to
462471
# trio.from_thread.run_sync()

0 commit comments

Comments
 (0)