Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion asgiref/sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -432,9 +432,11 @@ def __init__(
or iscoroutinefunction(getattr(func, "__call__", func))
):
raise TypeError("sync_to_async can only be applied to sync functions.")

functools.update_wrapper(self, func)
self.func = func
self.context = context
functools.update_wrapper(self, func)

self._thread_sensitive = thread_sensitive
markcoroutinefunction(self)
if thread_sensitive and executor is not None:
Expand Down
21 changes: 21 additions & 0 deletions tests/test_sync_contextvars.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,3 +138,24 @@ async def async_function():
sync_function = async_to_sync(async_function)
assert sync_function() == 42
assert foo.get() == "baz"


@pytest.mark.asyncio
async def test_sync_to_async_contextvars_with_callable_with_context_attribute():
"""
Tests that a callable object with a `context` attribute
can be wrapped with `sync_to_async` without overwriting the `context` attribute
and still returns the expected result.
"""
# Define sync Callable
class SyncCallable:
def __init__(self):
# Should not be copied to the SyncToAsync wrapper.
self.context = ...

def __call__(self):
return 42

async_function = sync_to_async(SyncCallable())
assert async_function.context is None
assert await async_function() == 42