Skip to content

Commit d1a0a2c

Browse files
authored
Merge pull request #1575 from guilledk/issue1573
Added helpful error message if an async function is passed to trio.to_thread_run_sync
2 parents 919624f + 3c27ee7 commit d1a0a2c

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
@@ -165,7 +165,17 @@ def do_release_then_return_result():
165165
def worker_fn():
166166
TOKEN_LOCAL.token = current_trio_token
167167
try:
168-
return sync_fn(*args)
168+
ret = sync_fn(*args)
169+
170+
if inspect.iscoroutine(ret):
171+
# Manually close coroutine to avoid RuntimeWarnings
172+
ret.close()
173+
raise TypeError(
174+
"Trio expected a sync function, but {!r} appears to be "
175+
"asynchronous".format(getattr(sync_fn, "__qualname__", sync_fn))
176+
)
177+
178+
return ret
169179
finally:
170180
del TOKEN_LOCAL.token
171181

trio/tests/test_threads.py

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

458458

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

0 commit comments

Comments
 (0)