Skip to content

Commit

Permalink
Disallow async callable class instances as callable for `sync.SyncToA…
Browse files Browse the repository at this point in the history
…sync` (#328)

i.e. passing an instance defining `async def __call__(...)` to `sync.SyncToAsync` will raise a `TypeError`
  • Loading branch information
flaeppe committed May 10, 2022
1 parent ab7379a commit df1e582
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
6 changes: 5 additions & 1 deletion asgiref/sync.py
Expand Up @@ -356,7 +356,11 @@ def __init__(
thread_sensitive: bool = True,
executor: Optional["ThreadPoolExecutor"] = None,
) -> None:
if not callable(func) or _iscoroutinefunction_or_partial(func):
if (
not callable(func)
or _iscoroutinefunction_or_partial(func)
or _iscoroutinefunction_or_partial(getattr(func, "__call__", func))
):
raise TypeError("sync_to_async can only be applied to sync functions.")
self.func = func
functools.update_wrapper(self, func)
Expand Down
12 changes: 12 additions & 0 deletions tests/test_sync.py
Expand Up @@ -99,6 +99,18 @@ async def test_function(*args):
)


@pytest.mark.asyncio
async def test_sync_to_async_raises_typeerror_for_async_callable_instance():
class CallableClass:
async def __call__(self):
return None

with pytest.raises(
TypeError, match="sync_to_async can only be applied to sync functions."
):
sync_to_async(CallableClass())


@pytest.mark.asyncio
async def test_sync_to_async_decorator():
"""
Expand Down

0 comments on commit df1e582

Please sign in to comment.