Skip to content

Commit d0ce78b

Browse files
committed
Switch async_to_sync type error to a warning
Detecting if a function is async in Python has a lot of false negatives, so this is a lot safer while async code we call all makes sure it has the coroutinefunction flag set.
1 parent 07bffa4 commit d0ce78b

2 files changed

Lines changed: 10 additions & 7 deletions

File tree

asgiref/sync.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import os
55
import sys
66
import threading
7+
import warnings
78
import weakref
89
from concurrent.futures import Future, ThreadPoolExecutor
910
from typing import Any, Callable, Dict, Optional, Union
@@ -118,7 +119,9 @@ class AsyncToSync:
118119

119120
def __init__(self, awaitable, force_new_loop=False):
120121
if not callable(awaitable) or not _iscoroutinefunction_or_partial(awaitable):
121-
raise TypeError("async_to_sync can only be applied to async functions.")
122+
# Python does not have very reliable detection of async functions
123+
# (lots of false negatives) so this is just a warning.
124+
warnings.warn("async_to_sync was passed a non-async-marked callable")
122125
self.awaitable = awaitable
123126
try:
124127
self.__self__ = self.awaitable.__self__

tests/test_sync.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -203,26 +203,26 @@ def test_async_to_sync_fail_non_function():
203203
"""
204204
async_to_sync raises a TypeError when applied to a non-function.
205205
"""
206-
with pytest.raises(TypeError) as excinfo:
206+
with pytest.warns(UserWarning) as warnings:
207207
async_to_sync(1)
208208

209-
assert excinfo.value.args == (
210-
"async_to_sync can only be applied to async functions.",
209+
assert warnings[0].message.args == (
210+
"async_to_sync was passed a non-async-marked callable",
211211
)
212212

213213

214214
def test_async_to_sync_fail_sync():
215215
"""
216216
async_to_sync raises a TypeError when applied to a sync function.
217217
"""
218-
with pytest.raises(TypeError) as excinfo:
218+
with pytest.warns(UserWarning) as warnings:
219219

220220
@async_to_sync
221221
def test_function(self):
222222
pass
223223

224-
assert excinfo.value.args == (
225-
"async_to_sync can only be applied to async functions.",
224+
assert warnings[0].message.args == (
225+
"async_to_sync was passed a non-async-marked callable",
226226
)
227227

228228

0 commit comments

Comments
 (0)